简单表单单选按钮 [英] Simple form radio button
问题描述
我正在使用 simple_form gem 并且非常喜欢它的简单性.但是,尝试设置一个简单的单选按钮超出了我的范围,因为我不断收到以下错误
i'm using the simple_form gem and really like its simplicity. However, trying to set to set up a simple radio button is beyond me as I keep getting the following error
未定义的局部变量或方法`vegan'"
1.这是我目前所拥有的
1.Here what I have so far
<%= f.collection_radio_buttons :diettype, [[vegan, 'vegan'] ,[vegetarian, 'vegetarian']]%>
2.这里是我在 simple_form 之前使用的带有更新/补丁方法的代码,它将更新和保存用户需求
2.Heres the code I used before simple_form with an update/patch method, which would update and save a users requirement
<%= f.label(:diettype, "Vegan") %>
<%= f.radio_button(:diettype, "Vegan") %>
<%= f.label(:diettype, "vegetarian") %>
<%= f.radio_button(:diettype, "vegetarian")%>
3.这就是我想要重现的内容
3.And here is what I am trying to reproduce
<select>
<option> vegan </option>
<option> Vegetarian </option>
</select>
注意 - 素食主义者和素食主义者是选择选项,它们将存储在 :diettype 的数据库列中.
NOTE - vegan and vegetarian are select options that will be stored in the database column of :diettype.
推荐答案
在你的 controller action
中,添加这一行
In your controller action
, add this line
def actionname
@types = ModelName.select(:diettype).distinct
..
end
哪里,
actionname
是渲染视图的操作.
ModelName
是您的模型的名称,其中包含 diettype
字段.
ModelName
is the name of your model which has diettype
field in it.
在您的视图
中,替换
<%= f.collection_radio_buttons :diettype, [[vegan, 'vegan'] ,[vegetarian, 'vegetarian']]%>
与
<%= f.collection_radio_buttons :diettype, @types, :diettype, :diettype %>
<%= f.collection_radio_buttons :diettype, @types, :diettype, :diettype %>
上一行的意思是:
创建一个单选按钮的集合,
Create a collection of radio buttons where,
1st :diettype
: 当你选择一个单选按钮时会设置变量
1st :diettype
: variable would be set when you select a radio button
@types
: 这个集合被传递
2nd :diettype
: 被选择的值
2nd :diettype
: the value that is being selected
3rd :diettype
: 按钮旁边的显示文本
3rd :diettype
: the display text beside the button
EDIT2
正如您指定的那样,您需要一个 静态集合
并且您没有从数据库中获取任何值:
As you specified that you need a static collection
and you are not taking any values from database :
只需在视图中添加以下行,无需更改控制器:
Simply add the following line in view, no need to change the controller :
<%= f.collection_radio_buttons :name, [['vegan', 'vegan'] ,['vegetarian', 'vegetarian']],:first, :last %>
这篇关于简单表单单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!