2

这最好通过例子来解释。以下操作很简单:

class Foo < ActiveRecord::Base
  has_many :bars
end

1a>> foo = Foo.new
=> #<Foo id: nil>
2a>> foo.bars << Bar.new
=> [#<Bar id: nil, foo_id: nil>]
3a>> foo.bars
=> [#<Bar id: nil, foo_id: nil>]

但是,我希望使用 Bar 初始化所有 Foo 对象,而不必显式运行第 2 行:

class Foo < ActiveRecord::Base
  has_many :bars

  # [...] Some code here
end

1b>> foo = Foo.new
=> #<Foo id: nil>
2b>> foo.bars
=> [#<Bar id: nil, foo_id: nil>]

这可能吗?理想情况下,“默认”对象仍将以与我明确运行第 2a 行相同的方式关联,以便在保存父 Foo 对象时保存它。

4

2 回答 2

2

让我先说从设计的角度来看,这可能不是最好的想法。假设您的代码比 Foo 和 Bar 复杂得多,那么您可能会朝着更像构建器的方向发展。

但是,如果您坚持按您的要求做,这将做到。

class Foo < ActiveRecord::Base
  has_many :bars

  def after_initialize 
    self.bars << Bar.new if self.new_record?
  end 
end
于 2010-07-05T16:59:11.560 回答
1

从概念上讲,这不是做这种事情的最干净的方法,因为您将模型逻辑混合到另一个模型逻辑中。

还有更多:初始化期间您还没有任何实例,所以我认为这是不可能的。

请记住,如果您需要保存关联的对象,您可以在控制器中或使用嵌套模型表单

你需要完成什么任务?

于 2010-07-05T16:51:56.657 回答