Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture error messages from ActiveRecord validations?

I'm creating a registration form using validation inside the User model such as

 validates_confirmation_of :password, :message = "Passwords do not match"
 validates_uniqueness_of :email, :message = "Email in use"

and register looks like this

def register
@user = User.new(params[:user])
  if @user.save
    redirect_to(:action => 'login')
  else
  end
end

I just have no idea how to return these messages to the user once they trigger any of these validations.

Any help would be greatly appreciated.

like image 771
user827570 Avatar asked Oct 22 '25 18:10

user827570


1 Answers

Well You dont have to explicitly do this If your validations fails they errors message is written into the the errors object for that object in your case @user

so Check

@user.errors.count() or @user.errors

To display the error message on the page

You could just iterate over the errors object

Edited :

<% @user.errors.full_messages.each do |message| %>

<%= message %>

<%end%>
like image 110
Viren Avatar answered Oct 24 '25 10:10

Viren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!