Reddirt
Reddirt

Reputation: 5953

Rails model create action shows id as nil

I have a Rails 3 app where in a Model I'm creating a Comment record.

I then want to email the new Comment.

This is my model code:

  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

But, newcomment variable doesn't show the comment.id

See this:

enter image description here

Thank for your help!

Upvotes: 2

Views: 2612

Answers (2)

Reddirt
Reddirt

Reputation: 5953

I moved the CommentMailer to the Comment model:

  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

Upvotes: 0

maximus ツ
maximus ツ

Reputation: 8065

This is because you are referring comment_id of object before saving object to db, since before_create execute in the context where record is not created/saved in the database.

Changing before_create :worequest_comment to after_create :worequest_comment should work

Upvotes: 2

Related Questions