Last time, we looked at having a specific button
in a form trigger a different action and method than the form
’s attributes dictate.
One way this can be used is to submit the form back to the new
action, and make adjustments on the server. This is a great way to dynamically load data if you have dependant fields like a country and a province/state:
<%= form_with model: @account do |form| %>
<!-- ... -->
<div>
<%= form.label :county %>
<%= form.select :country, options_for_country(@account.country) %>
<%= form.submit "Update Options",
formaction: new_account_path,
formmethod: :get %>
</div>
<div>
<%= form.label :province %>
<%= form.select :province,
options_for_province(@account.country, @account.province) %>
</div>
<!-- ... -->
<% end %>
If you click the “Update Options” button, instead of sending the form data to the create
action, it will be sent to the new
action:
class AccountsController < ApplicationController
def new
@account = Account.new(account_params)
end
def account_params
# param.require(:account).permit(:county, :province)
param.fetch(:account, {}).permit(:county, :province)
end
end
Note that our account_params
needs to use fetch
instead of require
since the params will be blank on first page load.