質問

次の場合:

Foo has_many:bars、:through => :baz

and

Foo accepts_nested_attributes_for:bar

新しい:bar を追加するときに find_or_create_by_name を実行したいが、 before_add 機能。

この質問の背景は 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)のようなものを試しましたが、それも機能しません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top