Radio button value in rails form_for not being part of params[:model]

时光怂恿深爱的人放手 提交于 2019-12-12 08:53:55

问题


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 %>

In my controller I have

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"}.

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!


回答1:


Try replacing your radio_button_tag calls with cust.radio_button so that Rails knows those radio buttons apply to your Customer model.

You can also simplify the :checked => (:gender == 'female')? true:false to just :checked => (:gender == 'female') because the == operator gives a boolean result.




回答2:


Use cust.radio_button instead radio_button_tag



来源:https://stackoverflow.com/questions/9420374/radio-button-value-in-rails-form-for-not-being-part-of-paramsmodel

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