开发者

after_add callback for has_one

开发者 https://www.devze.com 2023-01-17 02:17 出处:网络
This seems to be an inconsistency between has_many and has_one. The has_many association allows you to specify an after_add callback that is called after an object has been added to the collection.

This seems to be an inconsistency between has_many and has_one.

The has_many association allows you to specify an after_add callback that is called after an object has been added to the collection.

class Person
  has_many :parents, :after_add => { puts "Added new parent" } # allowed
  has_one :car, :after_add => { puts "Added car" } # not allowed
end

class Car
  after_create :assign_name
  def assign_name
    self.name = "Herbie"
 开发者_JS百科 end
end

Unfortunately, there isn't an after_add callback for the has_one association. How do you achieve the same thing for a has_one?


I think you can use before_save, and check if the car relation has changed:

before_save :do_something

def do_something
  puts "Added car" if car_changed?
end
0

精彩评论

暂无评论...
验证码 换一张
取 消