chell
chell

Reputation: 7866

after_create callback not firing on Model created with nested_attributes_for

I have two models:

class User
  has_many :submissions

  accepts_nested_attributes_for :submissions, :allow_destroy => true
end

class Submission
  belongs_to :user

  after_create :send_confirmation

  def send_confirmation
    UserMailer.confirm_submission(self)
  end
end

In the Controller the Submission model is created by the user model

def create
  @user = User.where(:email => user_params[:email]).first_or_create
  @user.update_attributes(user_params)
end

The after_create callback is not firing for the Submission model.

How can I get this callback to work?

Upvotes: 1

Views: 3495

Answers (2)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You have defined a after_create callback on the Submission class. I guess you expect than setting submissions attributes in your form to "create" a new submission.

But look at the code in the controller:

@user = User.where(:email => user_params[:email]).first_or_create
@user.update_attributes(user_params)

Here is what you are doing:

  1. Create a new User if not found
  2. Update user's instance with user_params

Assuming user_params contains your submissions attributes, you are not "creating" but "updating" the instance.

You need to define a after_update or after_save callback:

class Submission
  belongs_to :user

  after_save :send_confirmation

  def send_confirmation
    UserMailer.confirm_submission(self)
  end
end

Upvotes: 3

Rajarshi Das
Rajarshi Das

Reputation: 12320

Please try after_save instead of after_create

 class Submission    
  belongs_to :user

  after_save :send_confirmation

   def send_confirmation
    UserMailer.confirm_submission(self)
   end  
  end

thanks

Upvotes: 0

Related Questions