鉴于以下内容:

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,当我试图创建一个使用现有FooBar其给出错误。

有帮助吗?

解决方案

哇予一定累:

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