Form errors not displaying
In my model for users I am validating the presence of a number of attributes using:
validates_presence_of :parent_1_first_name, :parent_1_last_name...
The beginning of my form object looks like this:
<%= form_for @user, url: {action: 'update'} do |f| %> <% if @user.errors.any? %> <div class="form-errors"> <h2><%= pluralize(@user.errors.count, "error") %> stopped you from updating this user:</h2> <% @user.errors.full_messages.each do |msg| %> <h4><%= msg %></h4> <% end %> </div> <% end %>
My Update method in my User controller looks like this:
def update subaction = params[:subaction] if @user.update(edit_user_params) flash[:success] = "#{@user.first_name} #{@user.last_name} has been updated." redirect_to edit_user_path(@user, anchor: subaction) else flash[:error] = "Something went wrong and #{@user.first_name} #{@user.last_name} could not be updated. Please ensure all required fields have been filled out." redirect_to edit_user_path(@user) end end
When a user is updated, but is missing one of the fields I am checking form error messages do not display and instead I get a redirect to the edit path with my error message instead.
In googling around I don't see what I have setup incorrectly.
Hey RJ!
When you redirect, none of the variables are persisted over because you're making a totally new request. You must `render action: :edit` in the else clause in order to render the errors on the model.
When you redirect, none of the variables are persisted over because you're making a totally new request. You must `render action: :edit` in the else clause in order to render the errors on the model.
No problemo! It's one of those subtleties of Rails that you have to learn the frustrating / hard way. 😜