我有以下型号:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
在业务逻辑中,当初始化一个对象时foo f = Foo.new,也需要初始化三个条形。我怎样才能做到这一点?
我有以下型号:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
在业务逻辑中,当初始化一个对象时foo f = Foo.new,也需要初始化三个条形。我怎样才能做到这一点?
您可以after_create在您Foo.create的after_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
你可以:
代码将如下所示:
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 实例时被销毁。
您可以在类的initialize方法中定义它Foo。只要创建对象,初始化程序块就会运行Foo,您可以在该方法中创建相关对象。