Pre-save callback for associations

How do you call the before_save callbacks in the association when saving the parent? For instance:

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 the "before_save" call the user, but not the company. Thank.

+3
source share
1 answer

You can use this patch , which adds β€œtouch” functionality to the has_one association, or simply defines another after_save callback in the user model and β€œtap” the company instance explicitly there.

+2
source

Source: https://habr.com/ru/post/1751147/


All Articles