是否有“first_or_build"?has_many 关联的方法? [英] Is there a "first_or_build" method on has_many associations?

查看:26
本文介绍了是否有“first_or_build"?has_many 关联的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 rails 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

我觉得这非常有用,但我想在我的 has_many 关联上有一个 first_or_build 方法,它的作用类似于 first_or_initialize但是也像build那样在需要时向关联添加新记录.

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_initializefirst_or_create.事实是,first_or_initialize 不会像 build 那样将初始化记录添加到关联的目标中,而且 first_or_create ......好吧...... 创建记录,这不是意图.

update for clarification : yes, i know about first_or_initializeand first_or_create. Thing is, first_or_initializedoes 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

我只是想知道:

  • 针对此问题的内置解决方案已经存在?
  • 我的实现有我看不到的缺陷?

推荐答案

我不确定 rails 中是否有任何内置的东西可以完全满足您的需求,但是您可以使用比上面更简洁的扩展来模拟 first_or_initialize 代码您目前正在使用,我相信它可以满足您的需求,并将其包装成可重用的扩展,如下所示.这是用 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

这篇关于是否有“first_or_build"?has_many 关联的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆