【问题标题】:Rails 5.1.2 - form_with is not showing data-remote="true" in the htmlRails 5.1.2 - form_with 未在 html 中显示 data-remote="true"
【发布时间】:2017-07-20 17:47:01
【问题描述】:

Rails 5.1.2:

我正在尝试使用form_with 创建一个符合Rails documentationthis GitHub thread 的AJAX 表单。

这段代码:

<%= form_with url: '/' do |f| %>
<% end %>

事实上这段代码:

<%= form_with url: '/', remote: true do |f| %>
<% end %>

两者都产生这个 html:

<form action="/" accept-charset="UTF-8" method="post">
  <input name="utf8" type="hidden" value="..." />
  <input type="hidden" name="authenticity_token" value="..." />
</form>

为什么data-remote="true" 没有出现在 HTML 中,因为我发布的第一个链接表明它应该出现,我如何让它出现?

【问题讨论】:

  • 如果将url: '/' 更改为url: root_path 会发生什么?
  • 没有区别。

标签: ruby-on-rails ajax forms


【解决方案1】:

我在使用 Rails 5.1.4 应用时遇到了同样的问题。使用local: false 解决了这个问题。

<%= form_with url: '/', local: false do |f| %>
<% end %>

【讨论】:

  • 这个问题出现在 Rails 6 中,同样的解决方案修复了它。
  • 可以确认@RajeshM 评论。 gem 'rails', '~&gt; 6.1.1' 有同样的问题
【解决方案2】:

data-remote 的默认值由选项 Rails.application.config.action_view.form_with_generates_remote_forms 配置。默认情况下,Rails 5 中这个选项是true。在你所有的项目中搜索它,你似乎是从 Rails 4 或 smth 迁移过来的。否则覆盖此选项。

【讨论】:

  • 怀疑这是正确的答案,因为正如您所说,我升级了并且可以看到此选项(在 config/initializers/new_framework_defaults_5_1.rb 中找到)设置为 false。确认后将标记为正确。
  • 我在 Rails 5.1.6 的项目中的任何地方都找不到 form_with_generates_remote_forms(包括 config/initializers 或在 Rails 控制台中检查上述选项)。关于它可能在哪里或变量是否已重命名的任何提示?
【解决方案3】:

对我来说,将这两行添加到config/application.rb 修复了它:

# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2

【讨论】:

    【解决方案4】:

    Rails 5.1.2 默认情况下,form_with 假定您的表单将使用 Ajax。您可以通过在form_with 中传递:local 选项来选择退出此行为。

    <%= form_with url: '/' do |f| %>
    <% end %>
    

    以上代码产生

    <form action="/" accept-charset="UTF-8" data-remote="true" method="post">
      <input name="utf8" type="hidden" value="..." />
      <input type="hidden" name="authenticity_token" value="..." />
    </form>
    

    如果你想使用没有ajax的表单,你可以使用下面的方式 -

    <%= form_with url: '/', local: true do |f| %>
    <% end %>
    

    【讨论】:

    • 如您所见,这不是 OP 发生的情况
    • 我没听懂你想说什么?我检查了上面的代码并且它有效。 @SergioTulentsev
    • data-remote: "true",不是为 OP 生成的
    • 您可以阅读本文档特别部分 - (3.1.1. form_with) edgeguides.rubyonrails.org/…
    【解决方案5】:

    这将发生在 Rails 5.1 中

    我在 new_framework_defaults_5_1.rb 中的配置如下:

    # Make `form_with` generate non-remote forms.
    Rails.application.config.action_view.form_with_generates_remote_forms = false
    

    在我的视图文件中,我是这样使用的:

    = form_with(model: your_model , url: your_path, method: :post, local: false) do |f|
    ....your input here...
    

    现在您的 html 代码将在您的表单中生成 data-remote: true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 2020-08-12
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多