4

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?

1
  • 1
    Turbolinks causes all sorts of problems and I long ago stripped it out of my Rails apps. (Which isn't very helpful to you, I know!) The problem sounds like a typical Turbolinks caching issue - it tries to minimise changes to the page to speed page renders, but it does make mistakes when detecting what needs to change. One option might be to create a new instance variable in the controller called @errors or similar, and to reference the errors there? Commented Mar 30, 2022 at 11:29

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes - I'm sure this is the correct solution
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.