是否有与QUOT; first_or_build"方法对has_many关联? [英] Is there a "first_or_build" method on has_many associations?
问题描述
在轨3.2+,你可以这样做:
In rails 3.2+, you can do this :
SomeModel.some_scope.first_or_initialize
这意味着你也可以这样做:
Which means you can also do :
OtherModel.some_models.first_or_initialize
我觉得这是pretty的有用的,但我想对我的的has_many
first_or_build 方法>关联,这会像 first_or_initialize
不过的还添加了一个新的纪录协会评为建立
做的时候需要的。
I find this pretty useful, but i'd like to have a first_or_build
method on my has_many
associations, which would act like first_or_initialize
but also add a new record to the association as build
does when needed.
澄清更新:是的,我知道 first_or_initialize
和 first_or_create
。事情是, first_or_initialize
初始化记录不添加到该协会的目标为建立
确实,和 first_or_create
...好... 创建的记录,这不是目的。
update for clarification : yes, i know about first_or_initialize
and first_or_create
. Thing is, first_or_initialize
does not add the initialized record to the association's target as build
does, and first_or_create
... well... creates a record, which is not the intent.
我有一个解决方案,工程,采用联想扩展:
class OtherModel < ActiveRecord::Base
has_many :some_models do
def first_or_build( attributes = {}, options = {}, &block )
object = first_or_initialize( attributes, options, &block )
proxy_association.add_to_target( object ) if object.new_record?
object
end
end
end
我只是想知道:
- 内置解决这个问题已经存在?
- 在我的实现有缺陷,我不明白吗?
推荐答案
我不知道是否有任何内置的轨道,将做你想要什么,但你可以有更多的模仿first_or_initialize code简洁的扩展名不是你目前正在使用,我相信你想要做什么,并把它包装成一个可重用的扩展名,例如下面。这是写与Rails 3.2扩展格式。
I'm not sure if there is anything built into rails that will do exactly what you want, but you could mimic the first_or_initialize code with a more concise extension than you are currently using, which I believe does what you want, and wrap it into a reusable extension such as the following. This is written with the Rails 3.2 extend format.
module FirstOrBuild
def first_or_build(attributes = nil, options = {}, &block)
first || build(attributes, options, &block)
end
end
class OtherModel < ActiveRecord::Base
has_many :some_models, :extend => FirstOrBuild
end
这篇关于是否有与QUOT; first_or_build&QUOT;方法对has_many关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!