在rails中初始化另一个对象后创建相关对象

时间:2013-08-14 13:08:24

标签: ruby-on-rails activerecord ruby-on-rails-4

我有以下型号:

class Foo < ActiveRecord::Base
    has_many :bars
end

class Bar < ActiveRecord::Base
    belongs_to :foo
end

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

3 个答案:

答案 0 :(得分:4)

您可以在after_create

中使用Foo.create(在致电after_initialize之后)或Foo.new(致电Foo.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

答案 1 :(得分:3)

你可以:

  • 设置初始化Bar实例的after_initialize回调
  • 在has_many关联上设置附加:自动保存选项,以确保在保存父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

如果希望在销毁父Foo实例时销毁Bar实例,可以添加依赖选项:: destroy。

答案 2 :(得分:0)

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

相关问题