Home > Blockchain >  Rails 7 failed save only shows errors if I render with a status
Rails 7 failed save only shows errors if I render with a status

Time:02-23

I've been working with rails for a while, but I thought I'd try a course to cement my knowledge.

But I already get stumped on a basic save/error action.

I am trying to show error messages after model validation fails.

If the model validation fails, I render 'new'again, where the model instance should have error messages. But if I try to print the error messages like <%= modelinstance.errors.inspect %> it just shows an empty array.

The weird thing is, if I instead do render :new, status: :unprocessable_entity it gladly renders the whole error thing.

I was just wondering why this is the case, when the ruby on rails guide is allowing the string version.

Controller:

...
def index
    articles = Article.all

    render locals: {
        articles: articles
    }
end

def new
    @article = Article.new
end

def create
    @article = Article.new(article_params)

    if @article.save
        redirect_to @article
    else
        render :new, status: :unprocessable_entity
    end

end
...

View:

<h1>Create a new article</h1>

<% if @article.errors.any? %>
    <h2>The following errors prevented the article from saving:</h2>
    <% @article.errors.full_messages.each do |msg| %>
        <%= msg %>
    <% end %>
<% end %>

    ...
    <%= form_with scope: @article, url: articles_path, local: true do |f| %>
        <p>
            <%= f.label :title %>
            <%= f.text_field :title %>
        </p>
        <p>
            <%= f.label :description %>
            <%= f.text_area :description %>
        </p>
        <p>
         <%= f.submit %>
        </p>
    <% end %>'
    ...

CodePudding user response:

It's due to the introduction of Turbo in Rails 7. Without that status, Turbo wouldn't really know what to do with the redirects.

You can read more about it here: https://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission

Otherwise, you could just disable Turbo and it should go back to "normal".

  • Related