【问题标题】:In a Hotwire/Rails app, how to force a form helper to accept only text/html?在 Hotwire/Rails 应用程序中,如何强制表单助手只接受文本/html?
【发布时间】:2021-05-16 22:54:19
【问题描述】:

我已将 Hotwire 整合到我最新的 Rails 6 应用程序中。 Hotwire/Turbo 部分运行良好,但我有一个简单的用户表单,我不想使用 Hotwire/Turbo。目前,所有表单提交都在我的控制器中击中format.turbo_stream {},但我希望这个特定的表单改为击中format.html {} 块。我注意到表单提交请求上的Accept 标头现在自动包含text/vnd.turbo_stream.html,但我不确定如何删除它。

表单没有包裹在 turbo_frame_tag 中;页面上的任何地方都没有 Turbo,而且看起来很标准:

    <%= form_with model: @user do |f| %>
      <%= f.file_field :avatar, class: "file-input", id: "avatar-input" %>
      <%= f.text_field :name, class: "input wide", placeholder: "Your name here" %>

      <%= f.submit "Next", class: "button-next-submit" %>
    <% end %>

如何按表单强制执行此更改?我以前认为添加 turbo 标签是您更改行为/ Accept 标头的方式,但我现在看到,一旦您在控制器方法中添加 format.turbo_stream 块,表单就开始更喜欢它了。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6 hotwire-rails


    【解决方案1】:

    想通了。看起来大多数表单助手(form_withform_for 等)在选项哈希(documentation link)中接受 format 参数。您提供的值应该与您希望在控制器中命中的format.x 块相匹配。例如:

    # view.html.erb
    <%= form_with model: @user, format: :html do |f| %>
    ...
    <% end %>
    
    # controller.rb
    
    def update
      ...
      respond_to do |format|
        format.html {} # format: :html will hit this
        format.turbo_stream {} # format: :turbo_stream will hit this
        # format.json is also an option
      end
    end
    

    【讨论】:

      【解决方案2】:

      就我而言(rails 7)format: :html 还不够。对我有用的是turbo: false

      # view.html.erb
      <%= form_with model: @user, data: { turbo: false } do |f| %>
      ...
      <% end %>
      
      # controller.rb
      
      def update
        ...
        respond_to do |format|
          format.html {} # format: :html will hit this
          format.turbo_stream {} # format: :turbo_stream will hit this
          # format.json is also an option
        end
      end
      

      【讨论】:

      • 如果您在 turbo 框架内有链接,这也适用于 link_to 以防止 turbo 请求。
      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 2020-05-05
      • 2011-09-13
      • 2013-03-03
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多