Set local: true as default for form_with in Rails 5
Asked Answered
S

3

22

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 %>
Senna answered 14/12, 2017 at 22:8 Comment(2)
Did you ever solve this?Shipley
Not really. Had to set local: true to every formSenna
U
29

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
Unionize answered 3/8, 2018 at 6:21 Comment(2)
For posterity: This is a better solution than the one I suggested above (https://mcmap.net/q/571009/-set-local-true-as-default-for-form_with-in-rails-5)Pocked
Updated with more info on where to put the config (as per ecoologic's answer).Unionize
P
12

Consider overriding the form_with method:

# form_helper.rb
def form_with(options)
  options[:local] = true
  super options
end

That should solve it for every form in your application.

Pocked answered 26/3, 2018 at 13:26 Comment(0)
E
12

The Rails configurations can be set in config/application.rb file.

module App
  class Application < Rails::Application
    # [...]

    config.action_view.form_with_generates_remote_forms = false
  end
end

Guy C answer is good, but it's more idiomatic to put all config in this file rather than a separate initializer; That's where most of the Rails dev would expect it.

Note that this would spell disaster if you put it config/development.rb only or other env specific files.

Emmie answered 3/1, 2019 at 13:57 Comment(1)
This should be the accepted answer. +1 to changing configuration in the location where most developers would expect it.Louvar

© 2022 - 2024 — McMap. All rights reserved.