Definitely, there are many things to improve here, first let me explicitly answer your question:
validates: email, uniqueness: true
By adding that validation in your contact model, the update method will return false
so the email will not be updated. You can also ignore case_sensitivity by adding case_sensitive: false
to the validation.
You should keep in mind that this validation does not guarantee uniqueness if you have multiple servers/server processes (e.g. running Phusion Passenger, multiple Mongrels, etc) or a multi-threaded server. Please check this answer for an extended explanation.
However, that will not work on the code you paste above, let me explain why:
1) The update method requires passing 1 argument, so your code will throw an ArgumentError
there.
2) render
appears more than one time in the same method: This will throw you the following error
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
You will need to refactor your code there.
For redirect_to: root
, make sure to configure to root route first.
3) This line Contact.new(contact_params)
does not return an existing record. The new method creates an object instance, so you would not be updating anything there.
A possible solution for your method could be:
helper_method :contact
def update
if contact.update(contact_params)
flash[:success] = "Contact updated"
redirect_to :root
else
render :edit
end
end
private
def contact
@contact ||= Contact.find(params[:id])
end
Hope it helps.