我有一个模型(CustInfo),它包含3个属性:cust_name,age,gender。在我的编辑视图中,我使用form_for进行表单提交:
<%= 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
当我按提交按钮时,表单已提交,其参数如下:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"I9QEdP1mRr65wT9TRbzNokkaa+LHVyPfmgWJMKoup", "custinfo"=>{"age"=>"16", "cust_name"=>"jsmith"}, "gender"=>"M","commit"=>"Save"}.
看起来性别确实通过params传递,但它不在params [:model]中,在本例中为params [:custinfo],这就是更新函数不会更新此值的原因(因为我只有Cust .update_all(PARAMS [:custinfo]))。我的问题是为什么只有这个单选按钮不在params [:custinfo]中,而另外两个是?如何在params [:custinfo]中传递单选按钮值?谢谢!
答案 0 :(得分:5)
尝试用radio_button_tag
替换cust.radio_button
来电,以便Rails知道这些单选按钮适用于您的客户模式。
您还可以将:checked => (:gender == 'female')? true:false
简化为:checked => (:gender == 'female')
,因为==运算符会给出布尔结果。
答案 1 :(得分:1)
使用cust.radio_button而不是radio_button_tag