ravelinx ravelinx - 11 months ago 72
Ruby Question

Ruby - Radio button form for custom attribute

Let's say I have a class like this one:

class Something
has_and_belongs_to_many :categories
end


And the class category is something like this:

class Category
field :name
end


I am making a form where using radio buttons you can select what categories that something belongs to, my problem is how can I achieve that?

What I have tried is the following:

<table>
<% Category.all.each do |cat| %>
<tr>
<td>
<%= f.label :category, #{cat.name} %>
<%= f.radio_button, #{cat} %>
</td>
</tr>
<% end %>
</table>


I have tried other variations with "#{cat}" or "#{cat.name}" or just cat. These without any success.

Answer Source

Assuming this is your form (f.radio_button on the question) for Something model, you need to reference category_id on the form, try this:

<table>
  <% Category.all.each do |cat| %>
    <tr>
      <td>
        <%= f.radio_button :category_id, "#{cat.id}", :id => "radio-#{cat.id}" %>
        <label for="radio-#{cat.id}"><%= cat.name %></label>
      </td>
    </tr>
  <% end %>
</table>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download