开发者

Create instance of Rails model with has_many association prepopulated

This is best explained by example. The following is simple to do:

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>]

However, I want all Foo objects initialized with a Bar without having to explicitly run line 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>]

Is this possible? Ideally the 'default' object would still be associated in the same way as if I'd explicitly run line 2a, so that it gets saved when the parent Foo object is saved.


Let me preface this by saying that from a design perspective, this probably isn't the greatest idea. Assuming your code is much more complicated than Foo and Bar, you might be headed toward something more along the lines of a builder.

However, if you insist on doing what you ask, this will do it.

class Foo < ActiveRecord::Base
  has_many :bars

  def after_initialize 
    self.bars << Bar.new if self.new_record?
  end 
end


by concept, this isn't the cleanest way to do something like this, because you're mixing a model logic inside another one.

there's more: you haven't yet any instance during initialization, so I think this is not possible.

keep in mind that if you need to save associated objects, you can do it in controllers or using Nested Models Forms

what's the task you need to achieve?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜