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