创建 Rails 模型的实例,并预先填充 has_many 关联

发布于 2024-09-08 09:40:48 字数 640 浏览 3 评论 0原文

通过示例可以最好地解释这一点。以下操作很简单:

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 对象时保存它。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

棒棒糖 2024-09-15 09:40:48

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

但是,如果您坚持按照您的要求去做,这就会做到。

class Foo < ActiveRecord::Base
  has_many :bars

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

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
情痴 2024-09-15 09:40:48

从概念上讲,这不是执行此类操作的最干净方法,因为您将一个模型逻辑混合在另一个模型逻辑中。

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

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

您需要完成什么任务?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文