rails form_for中的单选按钮值不属于params [:model] [英] Radio button value in rails form_for not being part of params[:model]
问题描述
我有一个模型(CustInfo),其中包含3个属性:cust_name,年龄,性别.在我的编辑视图中,我使用form_for提交表单:
I have an model (CustInfo), which contains 3 attributes: cust_name, age, gender. In my edit view, I use form_for for form submission:
<%= form_for @cust[0] do |cust| %>
<label for="cname">Customer name: </label>
<%= cust.text_field :cust_name, :size => 20 %>
<label for="age">Customer age: </label>
<%= cust.text_field :age, :size => 5 %>
<label for="gender">Gender </label>
<%= radio_button_tag(:gender, "F", :checked => (:gender == 'female')? true:false) %><span style="float:left">F</span>
<%= radio_button_tag(:gender, "M", :checked => (:gender == 'male')? true:false) %><span style="float:left">M</span>
<%= cust.submit "Save" %>
<% end %>
在我的控制器中,
def update
if Cust.update_all(params[:custinfo])
flash[:notice] = "Successfully updated!"
redirect_to :action => "index"
else
flash[:notice] = "There are errors in the form, please try again"
render :action => "edit"
end
end
当我按下提交"按钮时,提交的表单及其参数如下:
When I press submit button, the form submitted, and its parameters are like this:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"I9QEdP1mRr65wT9TRbzNokkaa+LHVyPfmgWJMKoup", "custinfo"=>{"age"=>"16", "cust_name"=>"jsmith"}, "gender"=>"M","commit"=>"Save"}.
看起来性别确实可以通过参数传递,但是它不在参数[:model]内,在这种情况下,参数[:custinfo]也就不存在,这就是为什么update函数不会更新该值的原因(因为我只有Cust .update_all(params [:custinfo]).我的问题是,为什么只有这个单选按钮不在params [:custinfo]中,而其他两个在?以及如何在params [:custinfo]中传递单选按钮值?谢谢!
It looks like gender does get passed through params, but it's not within the params[:model], in this case params[:custinfo] and that's why the update function wouldn't update this value (because I only had Cust.update_all(params[:custinfo])). My question is that why only this radio button isn't in params[:custinfo], while the other two are? And how can I pass the radio button value inside params[:custinfo]? Thanks!
推荐答案
尝试将radio_button_tag
调用替换为cust.radio_button
,以使Rails知道这些单选按钮适用于您的Customer模型.
Try replacing your radio_button_tag
calls with cust.radio_button
so that Rails knows those radio buttons apply to your Customer model.
您还可以将:checked => (:gender == 'female')? true:false
简化为:checked => (:gender == 'female')
,因为==运算符可提供布尔结果.
You can also simplify the :checked => (:gender == 'female')? true:false
to just :checked => (:gender == 'female')
because the == operator gives a boolean result.
这篇关于rails form_for中的单选按钮值不属于params [:model]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!