ruby-on-railsruby

Why is "status: :unprocessable_entity" needed for displaying errors?


My controller-action looks this way:

def create
  @project = Project.new(set_params)

  if @project.save
    redirect_to projects_path
  else
     flash.now[: messages] = @project.errors.full_messages
     render: new, status::unprocessable_entity
  end
end

My view:

<%= form_with model: @project do |form| %>
    <% if @project.errors.any? %>
        <div class="errors">
            <h2><%= pluralize(@project.errors.count, "error") %> prohibited the operation.</h2>
            <ul>
                <% @project.errors.full_messages.each do |message| %>
                    <li><%= message %></li>
                <% end %>
            </ul>
        <div>
    <% end %>
    // ...

The way it is shown here, it works. Error-messages are displayed as expected.

When I remove "status: :unprocessable_entity" (behind "render :new") error-messages aren't shown anymore.

Somehow the status is needed additionally. As far as I know it sets some HTTP-status, which is then read by the browser.

Actually I would expect the errors-display feature to depend only on the @project.errors instance-variable. Means: If @project.errors has any values, then iterate over them.

What happens there? How does the HTTP-status interfere? How does the whole mechanism work?

Can someone share some insight?


Solution

  • Because you didn't share the error message, I can only guess what the problem might be.

    But the code has several syntax errors that I suggest fixing. Change

     flash.now[: messages] = @project.errors.full_messages
     render: new, status::unprocessable_entity
    

    to

     flash.now[:messages] = @project.errors.full_messages
     render :new, status: :unprocessable_entity
    

    Note the whitespaces and where the colons need to be.