如何使用 Rails 3 将单选按钮选择存储在我的数据库中?
我正在使用 Rails 3 和 Mongoid。
我能够存储文本字段和选择字段,但无法弄清楚如何在提交表单时在数据库中存储单选选项。这是我的代码...
模型
class Somerandomname
include Mongoid::Document
field :name
field :option
end
控制器
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
视图
<%= 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") %>
我的模型和控制器文件中需要什么才能将选择捕获到我的数据库中?
I 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将您的视图更改为:
这将导致生成的输入字段在 :somerandomname 中具有正确的 @name 命名空间。
Try changing your view to:
That will cause the generated input fields to have the proper @name namespaced within :somerandomname.
您的模型中可以有一个名为 option 的字段。在你的控制器中,你可以
根据选择的单选按钮来设置 params[:option] 的值(设置为所选单选按钮的值)。
you can have a field called option in your model. And in your controller you could do
depending on what radio button is selected the value of params[:option] will be set (to the value of the selected radio button).
就参数而言,单选按钮就像复选框一样:它们都有一个参数名称和选中时发送的值。唯一的区别是,一组特定的单选按钮在选中时会相互取消选中,因此只能选择其中一个。
因此,在您的示例中,您的数据库表中将有一个名为“option”的字段,该字段将从 params[:option] 设置,该字段等于“option1”、“option2”或“option3”。
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".