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)
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:
.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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With