How do I store radio button selection in my DB with Rails 3?
I开发者_StackOverflow中文版 am using Rails 3 and Mongoid.
I am able to store text fields and select fields but can't seen to figuer out how to store a radio option in the DB whe the form is submitted. Here is my code...
Model
class Somerandomname
include Mongoid::Document
field :name
field :option
end
Controller
def create
@somerandomname = current_user.somerandomnames.new(params[:somerandomname])
respond_to do |format|
if @somerandomname.save
format.html { redirect_to(@somerandomname, :notice => 'Somerandomname was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
View
<%= f.label :name , "Name:" %>
<%= f.text_field :name %>
<%= radio_button_tag(:option, "option1") %>
<%= label_tag(:option_option1, "option 1") %>
<br />
<%= radio_button_tag(:option, "option2") %>
<%= label_tag(:option_option2, "option 2") %>
What do I need in my model and controller file in order to capture the selection into my DB?
Try changing your view to:
<%= f.label :name , "Name:" %>
<%= f.text_field :name %>
<%= f.radio_button(:option, "option1") %>
<%= f.label(:option_option1, "option 1") %>
<br />
<%= f.radio_button(:option, "option2") %>
<%= f.label(:option_option2, "option 2") %>
That will cause the generated input fields to have the proper @name namespaced within :somerandomname.
you can have a field called option in your model. And in your controller you could do
model.option = params[:option]
model.save
depending on what radio button is selected the value of params[:option] will be set (to the value of the selected radio button).
As far as parameters go, radio buttons are just like checkboxes: they all have a parameter name and a value that they send through when checked. The only difference is that a particular group of radio buttons uncheck each other when checked, so that only one of them can be selected.
So, in your example you would have a field called 'option' in your db table, which would be set from params[:option] which would be equal to either "option1", "option2" or "option3".
精彩评论