Rails模型创建动作显示id为nil

时间:2015-04-15 16:36:15

标签: ruby-on-rails

我有一个Rails 3应用程序,在模型中我创建了一个Comment记录。

然后,我想通过电子邮件发送新的Comment

这是我的型号代码:

  before_create :worequest_comment

  protected
  def worequest_comment
    if self.workorder.worequest_id != nil
      if self.internal_only == false
        newcomment = Comment.create({:worequest_id => self.workorder.worequest_id, :comments => self.log_desc, :status_date => DateTime.now, :user_id => self.employee.user_id})
        CommentMailer.comment_email(newcomment).deliver if self.workorder.worequest.employee_id != nil
      end
    end
  end
end

但是,newcomment变量不显示comment.id

见:

enter image description here

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

这是因为您在将对象保存到db之前引用了对象的comment_id,因为before_create在未在数据库中创建/保存记录的上下文中执行。

before_create :worequest_comment更改为after_create :worequest_comment应该有效

答案 1 :(得分:0)

我将CommentMailer移动到了注释模型:

  after_create :comment_email

  protected
  def comment_email
    if !self.worequest.employee_id.nil?
      if Worequest.find(self.worequest_id).employee_id != nil
        Comment2Mailer.comment2_email(self.id).deliver
      end
      if Worequest.find(self.worequest_id).r_send == true
        CommentMailer.comment_email(self.id).deliver
      end
      if self.statuscode_id != nil
        Worequest.find(self.worequest_id).update_attributes(:statuscode_id => self.statuscode_id)
      end
    end
  end