How i Prevent Duplicate Entries in database at the time of form submit and display an alert box and stop form submission if entry is duplicate.
views:
26answers:
2
A:
You can add a validates_uniqueness_of
validation to your model:
class Model < ActiveRecord::Base
validates_uniqueness_of :column
end
John Topley
2010-07-09 12:27:30
A:
The more idiomatic Rails approach is to have a model validation for a set of attributes and then display the validation error messages after the form is submitted. By failing the validation the model is not saved to the database.
In the model
validates_uniqueness_of :some_attribute
In the form view
<% form_for @model do |f| %>
<%= f.error_messages %>
<% end %>
If you really want an alert box (which is a very in-your-face approach IMHO) then you might be better off using an AJAX submit in which you hook the form submit, make an AJAX call to the server to check the form validity by some means of your own, then process the server returned result. JQuery and its form plugin make this relatively easy to do
bjg
2010-07-09 12:31:55
You are correct but i need alert box when any duplicate entry insert by the user at the time of form submission.validates_uniqueness_of gives error in form not in alert box.
2010-07-09 12:38:47
@sachinrathore11 OK, then follow the AJAX approach but leverage the Rails validation facilities to do your checks with the `valid?` method
bjg
2010-07-09 15:07:29