Simple form radio button

不打扰是莪最后的温柔 提交于 2019-12-07 01:35:43

问题


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

"undefined local variable or method `vegan'"

1.Here what I have so far

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

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.And here is what I am trying to reproduce

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

NOTE - vegan and vegetarian are select options that will be stored in the database column of :diettype.


回答1:


In your controller action, add this line

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

where,

actionname is the action which is rendering your view.

ModelName is the name of your model which has diettype field in it.

In your view, replace

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

with

<%= f.collection_radio_buttons :diettype, @types, :diettype, :diettype %>

EDIT:

<%= f.collection_radio_buttons :diettype, @types, :diettype, :diettype %>

The above line means:

Create a collection of radio buttons where,

1st :diettype : variable would be set when you select a radio button

@types : this collection being passed

2nd :diettype : the value that is being selected

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



回答2:


This is the simplest solution for adding radio buttons with Simple Form that works great for me.

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


来源:https://stackoverflow.com/questions/21855709/simple-form-radio-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!