ruby on rails find_or_initialize

Is there any better way to achieve this in Ruby on Rails?

I'm searching for 11 fields and all are required also, and if not found initialize it.

There will be more required fields adding to it.

This query works perfect for me, but it just doesn't look like the best way to do this.

find_or_initialize_by_make_and_country_and_engine_and_power_and_body_and_doors_and_fuel_and_cylinders_and_transmission_and_gears_and_wheels(model,country,engine,power,body, doors, fuel, cylinders, transmission,gears,wheels)

Answers


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).first
record = new(attributes) unless record

On rails 3.2 I would do

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

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


Need Your Help

Flex execution timeout in AdvancedDataGrid

flex advanceddatagrid

I've a problem, I'm using an AdvancedDataGrid .

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.