Kevin Sylvestre
Kevin Sylvestre

Reputation: 38092

"Before Save" callback on associations

How do you call the "before_save" callbacks on an association when saving the parent object? For example:

class Company < ActiveRecord::Base
  belongs_to :user

  before_save Proc.new { ... } # Not called.
end

class User < ActiveRecord::Base
  has_one :company

  before_save Proc.new { ... } # Gets called.
end

params = { 
  :user => { 
    :name => "Kevin Sylvestre", 
    :company_attributes => { :city => "Waterloo", :region => "Ontario" } 
  }
}

@user = User.new(params[:user])
@user.save

Does calls "before_save" on the user, but not on the company. Thanks.

Upvotes: 4

Views: 4237

Answers (1)

Milan Novota
Milan Novota

Reputation: 15598

You can either use this patch that adds the "touch" functionality to the has_one association or just define another after_save callback in the User model and "touch" the Company instance explicitly there.

Upvotes: 2

Related Questions