ruby on rails find_or_initialize ruby on rails find_or_initialize ruby-on-rails ruby-on-rails

ruby on rails find_or_initialize


On rails 3.2 I would do

attributes = {}Model.where(attributes).first_or_initialize

Documentation http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize


Considering the sheer number of fields you are using, you probably are better off manually finding the record and initializing it if it does not exist:

attributes = {  country: country,  engine: engine,  power: power,  body: body  etc ...}record = where(attributes).firstrecord = new(attributes) unless record


You can define method like this in your model

def self.find_or_initialize_by_field(params)    send("find_or_initialize_by_#{params.keys.join("_and_")}", *params.values)end

and then you can call this method like

YourModel.find_or_initialize_by_field({country: country, engine: engine})