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!
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.
Use cust.radio_button instead radio_button_tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With