使用nested_attributes before_add回调
-
22-07-2019 - |
题
鉴于以下内容:
Foo has_many :bars, :through => :baz
和
Foo accepts_nested_attributes_for :bar
我希望做一个find_or_create_by_name
当我添加一个新的:bar
,但我不知道在哪里可以有某种before_add
功能。
这个问题的背景是Bar validates_uniqueness_of :name
,当我试图创建一个使用现有Foo
新Bar
其给出错误。
解决方案
哇予一定累:
class Foo < ActiveRecord::Base
has_many :bars, :through => :baz, :before_add => :some_callback
def some_callback(b)
#whatnot
end
end
但尽管如此,在some_callback
部分,该怎么办?我已经试过之类的东西b = Bar.find_or_create_by_name(b.name)
但这并不工作。
不隶属于 StackOverflow