Is there a “first_or_build” method on has_many associations?

前端 未结 1 350
有刺的猬
有刺的猬 2021-01-03 18:45

In rails 3.2+, you can do this :

SomeModel.some_scope.first_or_initialize

Which means you can also do :

OtherModel.some_mo         


        
相关标签:
1条回答
  • 2021-01-03 18:48

    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
    
    0 讨论(0)
提交回复
热议问题