【发布时间】:2013-05-27 11:03:05
【问题描述】:
在 rails 3.2+ 中,您可以这样做:
SomeModel.some_scope.first_or_initialize
这意味着你也可以这样做:
OtherModel.some_models.first_or_initialize
我发现这非常有用,但我想在我的 has_many 关联上使用 first_or_build 方法,它的作用类似于 first_or_initialize 但还向关联添加一条新记录为 @987654326 @ 在需要时执行。
澄清更新:是的,我知道first_or_initialize和first_or_create。问题是,first_or_initialize 没有像build 那样将初始化记录添加到关联的目标中,而first_or_create...嗯...创建一条记录,这不是本意。
我有一个可行的解决方案,使用关联扩展:
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
我只是想知道:
- 这个问题的内置解决方案已经存在?
- 我的实现有我看不到的缺陷?
【问题讨论】:
-
如果你想在某个时候在
OtherModel.some_models上执行急切的加载程序怎么办?我宁愿在after_initialize回调中执行这样的初始化,它更干净的方法 IMO。
标签: ruby-on-rails activerecord associations