Is there a way to pass params when clicking submit button in simple_form view in rails 3.2.12?

淺唱寂寞╮ 提交于 2019-12-17 16:16:00

问题


In simple_form view, the submit button is like this:

<%= f.button :submit, 'Save' %>

We are trying to pass a params subaction when clicking the Save button. The params[:subaction] should have value of 'update' after clicking the button. Here is what we tried in view but it did not work:

<%= f.button :submit, 'Save', :subaction => 'update' %>

Is there a way to pass a value in params[:subaction] when clicking the Save button?


回答1:


Use name and value option.

   <%= f.button  :submit , name: "subaction",value: "update"%>

In your controller you will get params[:subaction] with the value "update"




回答2:


as dax points out,

<%= hidden_field_tag(:subaction, 'update') %>
<%= f.button :submit, 'Save' %>

This will provide the string value 'update' to the routed controller action via the hidden field. It can then be retrieved by the controller with

params[:subaction]



回答3:


By specifying f.button :button, type: 'submit', we can use the name and value attributes as follows to submit using a single param. Notably, the value submitted (e.g., 'cake') may be different from the button text (e.g., 'The Best Cake').

_form.html.erb

<%= f.button :button, 'The Best Cake', type: 'submit', name: 'dessert_choice', value: 'cake' %>
<%= f.button :button, 'The Best Pie', type: 'submit', name: 'dessert_choice', value: 'pie' %>

Controller

def controller_action
  dessert_choice = params[:dessert_choice] # 'cake' or 'pie'
end

This approach avoids the need for hidden inputs as @dax mentioned in the comment above.

Tested on Simple Form 3.3.1 with Rails 4.2.



来源:https://stackoverflow.com/questions/17916316/is-there-a-way-to-pass-params-when-clicking-submit-button-in-simple-form-view-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!