user827570
user827570

Reputation: 491

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.

Upvotes: 4

Views: 7491

Answers (1)

Viren
Viren

Reputation: 5962

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%>

Upvotes: 9

Related Questions