Samuel Cambridge
Samuel Cambridge

Reputation: 73

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)

Upvotes: 6

Views: 9691

Answers (4)

Casper
Casper

Reputation: 34338

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:

Upvotes: 10

Mohamed ALOUANE
Mohamed ALOUANE

Reputation: 5407

This one work for me :

<html>
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |key, value| %>
        <div class="alert alert-<%= key %>"><%= value %></div>
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
    </div>

  </body>
</html>

Upvotes: 0

Pankaj Bhambhani
Pankaj Bhambhani

Reputation: 679

interest.errors.messages.join(<any concatenating character>) will create a string concatenating your array elements.

You can use a string - such as ", " , ": " or pretty much anything to concatenate.

Upvotes: -1

Trip
Trip

Reputation: 27124

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

Upvotes: 4

Related Questions