将 local: true 设置为 Rails 5 中 form_with 的默认值 [英] Set local: true as default for form_with in Rails 5

查看:28
本文介绍了将 local: true 设置为 Rails 5 中 form_with 的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个项目,在该项目中我们不会使用 ajax 调用来提交表单,因此我需要将 local: true 放在项目中的每个表单中,如rails 文档:>

:local - 默认情况下,表单提交是远程且不显眼的 XHR.使用 local: true 禁用远程提交.

有没有办法将本地选项默认设置为true?

我们正在使用 Rails 5 form_with 助手,如下所示:

<%= form_with(model: @user, local: true) do |f|%><div><%= f.label :name %><%= f.text_field :name %>

<div><%= f.label :email %><%= f.email_field :email %>

<%= f.submit %><%结束%>

解决方案

正如您所说,它可以使用 local: true 在每个表单的基础上进行设置.但是可以使用配置选项[form_with_generates_remote_forms][1] 全局设置它.此设置确定 form_with 是否生成远程表单.默认为 true.

这个配置放在哪里?Rails 提供了四个标准点来放置这样的配置.但是您可能希望在所有环境(即开发、生产等)中使用此配置.所以要么在初始化程序中设置它:

# config/initializers/action_view.rbRails.application.config.action_view.form_with_generates_remote_forms = false

或者更常见的设置在 config/application.rb 中.

# config/application.rb模块应用类应用

I'm working on a project where we won't be using ajax calls for submitting the forms, so I need to put local: true in every form in the project, as indicated in the rails docs:

:local - By default form submits are remote and unobstrusive XHRs. Disable remote submits with local: true.

Is there any way to set the local option as true by default?

We're using Rails 5 form_with helper like this:

<%= form_with(model: @user, local: true) do |f| %>
    <div>
        <%= f.label :name %>
        <%= f.text_field :name %>
    </div>

    <div>
        <%= f.label :email %>
        <%= f.email_field :email %>
    </div>
    <%= f.submit %>
<% end %>

解决方案

As you've stated it can be set on a per form basis with local: true. However it can be set it globally use the configuration option [form_with_generates_remote_forms][1]. This setting determines whether form_with generates remote forms or not. It defaults to true.

Where to put this configuration? Rails offers four standard spots to place configurations like this. But you probably want this configuration in all enviroments (i.e. development, production, ...). So either set it in an initializer:

# config/initializers/action_view.rb
Rails.application.config.action_view.form_with_generates_remote_forms = false

Or maybe more commonly set in config/application.rb.

# config/application.rb
module App
  class Application < Rails::Application
    # [...]

    config.action_view.form_with_generates_remote_forms = false
  end
end

这篇关于将 local: true 设置为 Rails 5 中 form_with 的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆