Reputation: 3527
I have a form that creates a new device based on the name of the device entered by the user, as well as some other data. I want to run a query on my Devices to see if the name they entered already exists so that they may not create a device with duplicate names. No matter how I set up a query to do the search, the method always states that the device already exists, even if it doesn't. With out the conditional statement, the code creates devices appropriately. Any ideas how I can work this out?
The method in Device controller:
def create
if Device.where('name' => params[:name])
respond_to do |format|
format.html { redirect_to :back, notice: 'Cannot create device. It already exists.' }
end
else
#Code that creates device
#respond_to code
end
end
Upvotes: 0
Views: 62
Reputation: 11444
You should use model-level validation to prevent duplicate data.
class Device < ActiveRecord::Base
validates_uniqueness_of :name, :message => 'already exists'
...
end
That way in your controller you can base decisions on the save
method.
@device = params[:device]
respond_to do |format|
if @device.save
format.html # successful save
else
format.html { render action: 'new' }
end
end
Upvotes: 1
Reputation: 6088
The reason why it always passes is because it returns a empty array and if []
will return true. To see if a user with that name exists you could use this:
Device.where(:name => params[:name]).exists?
but you shouldn't do it like that. You should use validations:
validates :name, :uniqueness => true
Check the guides for more insight about validations and how to use them: http://guides.rubyonrails.org/active_record_validations_callbacks.html
Also see the second answer for the more detailed explanation, and stuff like this is nicely explained in this book: http://ruby.railstutorial.org/chapters/modeling-users#sec-presence_validation
Upvotes: 1