Ask A Question

Notifications

You’re not receiving notifications from this thread.

Form errors not displaying

RJ McCollam asked in Rails
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.
Reply
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.
Reply
Ah, thank you Chris. Updated that and I am all set. Really appreciate you answering.
Reply
No problemo! It's one of those subtleties of Rails that you have to learn the frustrating / hard way. 😜
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.