0

我有以下型号:

class Foo < ActiveRecord::Base
    has_many :bars
end

class Bar < ActiveRecord::Base
    belongs_to :foo
end

在业务逻辑中,当初始化一个对象时foo f = Foo.new,也需要初始化三个条形。我怎样才能做到这一点?

4

3 回答 3

4

您可以after_create在您Foo.createafter_initializeFoo.newFoo.rb

after_create :create_bars

def create_bars 
  3.times  do
   self.bars.create!({})
  end
end

或者:

after_initialize :create_bars

def create_bars 
  3.times  do
   self.bars.new({})
  end if new_record?
end
于 2013-08-14T13:22:45.063 回答
3

你可以:

  • 设置一个初始化 Bar 实例的 after_initialize 回调
  • 在 has_many 关联上设置附加 :autosave 选项,以确保在保存父 foo 时保存子 Bar 实例

代码将如下所示:

class Foo < ActiveRecord::Base
  has_many :bars, autosave: true

  after_initialize :init_bars

  def init_bars
    # you only wish to add bars on the newly instantiated Foo instances
    if new_record?
      3.times { bars.build }
    end
  end

end

您可以添加选项dependent: :destroy 如果您希望 Bar 实例在您销毁父 Foo 实例时被销毁。

于 2013-08-14T13:35:56.243 回答
0

您可以在类的initialize方法中定义它Foo。只要创建对象,初始化程序块就会运行Foo,您可以在该方法中创建相关对象。

于 2013-08-14T13:20:07.710 回答