0

我正在尝试提交表单并在 rails 7.0 应用程序上返回 turbo_stream。在我的表格中,我有以下内容。

 <%= form_with url: "/request_trial", method: :post, format: :turbo_stream do |form| %>
  <%= form.label :name, I18n.t('marketing.form.name'), class: 'form-label required' %>
  <%= form.text_field :name, class:"form-control", required: true %>

  <%= form.submit I18n.t('marketing.form.send'), class: 'btn btn-trial'  %>
<% end %>

在我的控制器中,我有以下内容

respond_to do |format|
  format.turbo_stream do |format|
    render turbo_stream: turbo_stream.replace(:'marketing-request-trial-form',
                                              partial: 'marketing/request_trial')
  end
end

这给了我一个错误ActionController::UnknownFormat

尽管我在表单中指定了格式,但似乎格式是html我提交表单时的格式。

我可以看到这是从哪里来的,在我的请求标头上,我有以下内容

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

我需要在请求标头上添加text/vnd.turbo-stream.html类型,我该怎么做?

4

1 回答 1

1
  • 你需要强调格式类型
format.turbo_stream do
   render turbo_stream: turbo_stream.replace(@article, partial: 'welcome/form')
end
class WelcomeController < ApplicationController

  def index
    @article = Article.first
  end

  def update_article
    @article = Article.find(article_params[:id])
    respond_to do |format|
      if @article.update(article_params)
        format.turbo_stream do
          render turbo_stream: turbo_stream.replace(@article, partial: 'welcome/form')
        end
      end

    end
  end

  def article_params
    params.require(:article).permit(:id,:title, :body)
  end
end
  • index.html.erb
<h1>Welcome ! This is a tutorial about Rails forms</h1>
<%= turbo_frame_tag dom_id(@article) do %>
  <%= form_with  model: @article, url: update_article_path, method: :post, format: :turbo_stream do |form| %>
    <%= form.text_field :id %>
    <%= form.text_field :title %>
    <%= form.text_field :body %>
    <%= form.submit "Update" %>
  <% end %>
<% end %>
  • _form.html.erb
<%= turbo_frame_tag dom_id(@article) do %>
  <h1>New Book</h1>
  <div class="card card-body">
    <label>title</label>
    <input value="<%= @article.title %>">
  </div>
<% end %>
  • 架构.rb
ActiveRecord::Schema[7.0].define(version: 2022_02_16_084944) do
  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end
于 2022-02-16T09:16:20.817 回答