【问题标题】:Simple form radio button简单表单单选按钮
【发布时间】:2014-02-18 13:44:10
【问题描述】:

我正在使用 simple_form gem,非常喜欢它的简单性。但是,尝试设置一个简单的单选按钮超出了我的范围,因为我不断收到以下错误

“未定义的局部变量或方法‘vegan’”

1.这是我目前所拥有的

 <%= f.collection_radio_buttons :diettype, [[vegan, 'vegan'] ,[vegetarian, 'vegetarian']]%>

2.这是我在 simple_form 之前使用的带有更新/补丁方法的代码,它将更新并保存用户需求

 <%= f.label(:diettype, "Vegan") %>
 <%= f.radio_button(:diettype, "Vegan") %>
 <%= f.label(:diettype, "vegetarian") %>
 <%= f.radio_button(:diettype, "vegetarian")%>

3.这就是我要重现的内容

<select>
   <option> vegan </option>
   <option> Vegetarian </option>
</select>

注意 - vegan 和 Vegan 是选择选项,将存储在 :diettype 的数据库列中。

【问题讨论】:

  • 什么是素食主义者和素食主义者?
  • 它们是我的表单的单选按钮,我希望用户选择
  • 尝试:[['vegan','vegan'],['vegetarian','vegetarian']]。或者:[[f.vegan,'vegan']] 如果是数据库字段
  • 这些选项将存储在上面提到的 :diettype 的数据库列中

标签: ruby-on-rails simple-form


【解决方案1】:

在您的controller action 中,添加这一行

  def actionname
    @types = ModelName.select(:diettype).distinct
    ..
  end

在哪里,

actionname 是呈现视图的操作。

ModelName 是您的模型的名称,其中包含 diettype 字段。

在你的view,替换

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

上面一行的意思是:

在哪里创建单选按钮的集合,

1st :diettype :当您选择单选按钮时将设置变量

@types : 这个集合被传递了

2nd :diettype : 被选中的值

3rd :diettype : 按钮旁边的显示文字

EDIT2

正如您指定的那样,您需要 static collection 并且您没有从数据库中获取任何值:

只需在视图中添加以下行,无需更改控制器:

<%= f.collection_radio_buttons :name, [['vegan', 'vegan'] ,['vegetarian', 'vegetarian']],:first, :last %> 

【讨论】:

  • 你能解释一下这行代码吗?
  • 您的表的diettype column 中有任何值吗?如果您的集合为空,即@types = nil,则会引发该错误。正如你所说的select options that will be stored in the database column of :diettype,我使用了@types。因此,它们应该存在以显示列表。
  • 请看我的编辑。我想提交从选择选项中选择的 veganvegetarian 值到 :diettype coloum
  • @samsos 好的。所以你需要以veganvegetarian 作为值的静态集合。我会更新答案。
  • 嘿,在尝试使用此解决方案时,我收到一条错误消息,指出我正在尝试在我的模型上调用私有方法选择。我错过了什么?
【解决方案2】:

这是使用简单表单添加单选按钮的最简单解决方案,非常适合我。

 <%= f.input :diettype, as: :radio_buttons, collection: ['Vegan', 'Vegetarian'] %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多