Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show error message in Flash alert Rails 3

If I set a validation message up within my model

validates :name, :presence => {:message => 'The name cant be blank.'}

How do I get that message to show up in a flash alert, this is what i have tried so far

def create
   @message = Message.new(params[:message])
   if @message.valid?
     ContactMailer.send_mail(@message).deliver
     redirect_to(root_path, :notice => "Thanks for your message, I will be in touch soon")
   else
     flash[:error] = @message.errors
     render :new
   end
end

but all i get is a black error message strip at the top of the page with no text in it, in my layout/application i have this

<% flash.each do |name, msg| %>
<div class="alert alert-<%= name == :notice ? "success" : "error" %>">
  <%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
</div>

Any pointers appreciated

like image 819
Richlewis Avatar asked Jul 18 '13 10:07

Richlewis


1 Answers

This is not good idea to show validation errors through the flash message, but if you really need it:

flash.now[:error] = @message.errors[:name].first

You should use flash.now[:error] in case if you need to show message immediately.

http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-5B-5D

like image 155
ole Avatar answered Nov 11 '22 04:11

ole