rails7 render new 不显示错误


In rails 7 forms are submitting as TURBO_STREAM by default. After submitting a form Turbo expects a redirect unless response status is in 400-599 range.

render :new  # default status is 200

With status code 200 Turbo shows an error in the browser console and page doesn't re-render.

To make Turbo accept rendered html, change the response status. Default seems to be :unprocessable_entity (status code 422)

render :new, status: :unprocessable_entity

Update: a note on "Content-Type". This applies to default form submission with turbo.

In this set up turbo is expecting an html response with Content-Type: text/html;. @puerile noted that omitting .html extension in your views also breaks the response.

Rails uses .html extension to set response content type to text/html. When extension is omitted content type is set to text/vnd.turbo-stream.html because the form is submitted as TURBO_STREAM, since our response doesn't have a <turbo-stream> it is the wrong content type.

>> Mime[:turbo_stream].to_str
=> "text/vnd.turbo-stream.html"

If we have a view views/users/new.erb, this will not work:

if @user.save
  redirect_to @user
else
  # NOTE: this will render `new.erb` and set 
  #       `Content-Type: text/vnd.turbo-stream.html` header;
  #       turbo is not happy.
  render :new, status: :unprocessable_entity
end

To fix it, use respond_to method:

respond_to do |format|
  if @user.save
    format.html { redirect_to @user }
  else
    # NOTE: this will render `new.erb` and set 
    #       `Content-Type: text/html` header;
    #       turbo is happy.
    format.html { render(:new, status: :unprocessable_entity) }
  end
end

or set content type manually:

if @user.save
  redirect_to @user
else
  render :new, status: :unprocessable_entity, content_type: "text/html"

  # NOTE: you can also set headers like this
  headers["Content-Type"] = "text/html"
end

One caveat with the last set up is that the layout has to be without .html extension as well, otherwise, render :new will render new.erb without a layout and turbo won't be happy again. This is not an issue when using respond_to method.

https://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to

From : https://stackoverflow.com/questions/71751952/rails-7-signup-form-doesnt-show-error-messages
阅读量: 307
发布于:
修改于: