Reputation: 1242
Is there a way to use find_or_initialize_by but pass it a hash of params and have it search on those?
I have a form that allows a user to create a Car, and specify different components for that Car (Car.engine_type, Car.model, etc). The user could only specific one component (Car.engine_type) or they could submit multiples. However, I want to be able to find if a Car already exists with those components so I'm not creating duplicates.
I'm aware of find_or_initialize_by but my problem is that I don't know at runtime what model attributes will be submitted, so I can't use that dynamic finder. One submittal could be Car => {engine_type ="V6"}. Another submittal could be Car => {num_doors=>"4",model=>"Ford"}
Upvotes: 2
Views: 489
Reputation: 13332
I dont know if you can do it in one line, but do you really need to? how about something like this:
cars = Car.where(params[:car])
if cars.any?
@car = cars.first
else
@car = Car.create(params[:car])
end
Upvotes: 2