gpt4 book ai didi

ruby-on-rails - has_one 的 after_add 回调

转载 作者:行者123 更新时间:2023-12-01 05:43:39 25 4
gpt4 key购买 nike

这似乎是 has_many 和 has_one 之间的不一致。

has_many 关联允许您指定一个 after_add 回调,该回调在将对象添加到集合后调用。

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"
end
end

不幸的是, has_one 关联没有 after_add 回调。你如何为 has_one 实现同样的目标?

最佳答案

我认为您可以使用 before_save,并检查汽车关系是否已更改:

before_save :do_something

def do_something
puts "Added car" if car_changed?
end

关于ruby-on-rails - has_one 的 after_add 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com