创建 Rails 模型的实例,并预先填充 has_many 关联
通过示例可以最好地解释这一点。以下操作很简单:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先我要说的是,从设计的角度来看,这可能不是最好的想法。假设您的代码比 Foo 和 Bar 复杂得多,您可能会朝着 的方向发展。
但是,如果您坚持按照您的要求去做,这就会做到。
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.
从概念上讲,这不是执行此类操作的最干净方法,因为您将一个模型逻辑混合在另一个模型逻辑中。
还有更多:在初始化期间您还没有任何实例,所以我认为这是不可能的。
请记住,如果您需要保存关联的对象,您可以在控制器中或使用嵌套模型表单来完成,
您需要完成什么任务?
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?