nested_attributesを使用するbefore_addコールバック
-
22-07-2019 - |
質問
次の場合:
Foo has_many:bars、:through => :baz
and
Foo accepts_nested_attributes_for:bar
新しい:bar
を追加するときに find_or_create_by_name
を実行したいが、 before_add のようなものがある場所がわからないcode>機能。
この質問の背景は Bar validates_uniqueness_of:name
です。既存の Bar を使用している新しい
Foo
を作成しようとするとエラーが発生します。 code>。
解決
うんざりしなければなりません:
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