Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Validation Errors

I've set up a small app that takes an email address and saves it, I've set up validation on the model (unique and valid email) and these both work.

I'm using the below code to try save the email, if it already exists or its not a valid format it needs to stop and set the error message

def create
    interest = KnownInterest.new( :email => params[:email] )
    if(interest.valid? and interest.save)
        flash[:notice] = "Thanks for showing interest, We'll be in touch with updates."
    else
        flash[:notice] = interest.errors.messages
    end     
    redirect_to action: "index"
end

this spits out ["Email not valid"], how do i get this to be a string (not what I think is an array, correct me if I'm wrong)

like image 345
Samuel Cambridge Avatar asked Jun 30 '12 10:06

Samuel Cambridge


2 Answers

If you just want the first message then interest.errors.messages.first. If you want them all then something like interest.errors.full_messages.join(", ") will group all the messages into one string.

However you might want to brush up on ActiveRecord validations and errors.
Here's a pretty good guide:

http://guides.rubyonrails.org/active_record_validations_callbacks.html

Read at least:

  • Section 7: Working With Validation Errors
  • Section 8: Displaying Validation Errors
like image 124
Casper Avatar answered Nov 05 '22 07:11

Casper


.messages will return an array of all your errors. Even if its just one.

So to properly display them, do this in your view :

- for error in flash[:notice] do
  = error

Or if you prefer html.erb :

<%- for error in flash[:notice] do %>
    <%= error %>
<%- end %>
like image 20
Trip Avatar answered Nov 05 '22 06:11

Trip