Is there a “first_or_build” method on has_many associations?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)