Reputation: 13907
So I have a form in my Rails app that's on a _form.html.erb
.
I'm displaying this partial on every page of my site, so it doesn't really have any model logic behind it, and the User created form it is made on the fly in the view:
<%= form_for User.new, :validate => true do |f| %>
<table>
<tr>
<td><%= f.label :invitation_token, "Invite Token" %></td>
<td><%= f.text_field :invitation_token, :placeholder => "From your inbox…".html_safe %></td>
</tr>
<tr>
<td colspan="2"><br><%= f.submit "Sign Up" %></td>
</tr>
</table>
<% end %>
I have some validations in my User model, but how would I display those validation errors in my view after reload?
I've tried User.new.errors.inspect
but the messages parameter is always empty, even if there's a validation error.
Upvotes: 1
Views: 278
Reputation: 6852
There are a few ways to do this. Since you will likely want to render these error messages in many places, create a shared folder in your views app/views/shared/_error_messages.html.erb
and add this partial:
<% if object.errors.any? %>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
<% end %>
Now in your view add the code to render the error messages in you form just below form for
<%= render 'shared/error_messages', object: f.object %>
Upvotes: 2