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) 

4 Answers

On rails 3.2 I would do

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

Documentation

6

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 

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}) 

while using find_or_intialize_by

find by key fields , dont assign all the feilds at once

eg I assume the make is the key field in the model

car = find_or_initialize_by_make(model) car.update_attributes(country: country,engine: engine,power: power, body: body,doors: doors ,fuel: fuel,cylinders:cylinders,transmission: transmission, gears: gears, wheels: wheels) 

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.