新手问题 ActionMailer (Gmail) 如果发送邮件失败如何能够 rollback 当前提交的数据库变更呢

n00b1 · 2013年12月23日 · 最后由 lulalala 回复于 2013年12月24日 · 2289 次阅读

我的如下这段代码即使邮件发送不成功,也会创建一个新的 post,请问如何如果投送邮件失败,将这条 post.save rollback 呢?

def create
  @post = post.new(post_params)
  @post.user = current_user
  if @post.save
    begin
    AppMailer.notify_on_new_post(current_user, @post).deliver
    flash[:notice] = 'Post Created'
    rescue Exception
      flash[:error] = 'Oops, problems sending the mail'
    end
    redirect_to user_path(@post.user)
  else
    render :new
  end
end

你这代码槽点很多,但是头痛医头脚痛医脚的话,在 rescue 里面把 post 杀了就好了

#1 楼 @xstmjh 非常感谢,果然简单直接,@post.delete即可,我还在看 Post.transaction ActiveRecord::RollBack end...

放在 Post.transaction 中,一旦 raise exception,就 rollback

把寄信邏輯放在 Post 中的 after_create,理論上寄出問題就會自動 rollback

需要 登录 后方可回复, 如果你还没有账号请 注册新账号