ReggieB
ReggieB

Reputation: 8257

Errors not displaying when rendering edit in Rails 7

My app is running Rails Rails 7.0.2.3

In my update controller action I have the line:

return render(:edit) unless @user_form.save

This renders the edit view on error .... but errors are not displayed.

In my edit view I am defining the form with:

form_for @user_form, url: user_path(@user_form), method: :patch do |f|

The form submits via turbo. I can see the error being added to @user_form.errors in the controller, but the instance of @user_form in the view is not changing on each form submission. If I output @user_form.inspect to the view - the id remains the same on each submission.

I have tried adding remote: false to the form_for call, but this does not seem to have an effect.

The only solution I have found is to add data: { turbo: false } to the form_for call.

Is there a better way of handling this?

Upvotes: 3

Views: 1536

Answers (2)

George Yacoub
George Yacoub

Reputation: 1456

You need to render with status: :unprocessable_entity. I think the change in status invalidates the cache.

so change your code to:

return render(:edit, status: :unprocessable_entity) unless @user_form.save

Upvotes: 3

Matt Budz
Matt Budz

Reputation: 247

you'll want to use a partial to show the errors.

you'll need to add an update.turbo_stream.erb file to this view's directory. In that file have something like:

<%= turbo_stream.update 'id_of_div_where_you_want_to_show_errors' do %>
   <%= render partial: 'partial_that_displays_errors' %>
<% end %>

or your controllers update action you'll want to have something like

respond_to do |format|
  format.turbo_stream { turbo_stream.update 'id_of_div_where_you_want_to_show_errors', render partial: 'partial_that_displays_errors' %>
end

Treat all this more like pseudocode and apply it to your own app, it's hard to say what's going on without seeing your code.

Upvotes: 0

Related Questions