Ruby - 自定义属性的单选按钮形式
Ruby - Radio button form for custom attribute
假设我有一个像这样的 class:
class Something
has_and_belongs_to_many :categories
end
class 类别是这样的:
class Category
field :name
end
我正在制作一个表单,您可以在其中使用单选按钮 select 某物属于什么类别,我的问题是我该如何实现?
我试过的是:
<table>
<% Category.all.each do |cat| %>
<tr>
<td>
<%= f.label :category, #{cat.name} %>
<%= f.radio_button, #{cat} %>
</td>
</tr>
<% end %>
</table>
我尝试过使用“#{cat}”或“#{cat.name}”或只是 cat 的其他变体。这些都没有成功。
假设这是 Something
模型的表格(问题 f.radio_button
),您需要在表格中引用 category_id
,试试这个:
<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>
假设我有一个像这样的 class:
class Something
has_and_belongs_to_many :categories
end
class 类别是这样的:
class Category
field :name
end
我正在制作一个表单,您可以在其中使用单选按钮 select 某物属于什么类别,我的问题是我该如何实现?
我试过的是:
<table>
<% Category.all.each do |cat| %>
<tr>
<td>
<%= f.label :category, #{cat.name} %>
<%= f.radio_button, #{cat} %>
</td>
</tr>
<% end %>
</table>
我尝试过使用“#{cat}”或“#{cat.name}”或只是 cat 的其他变体。这些都没有成功。
假设这是 Something
模型的表格(问题 f.radio_button
),您需要在表格中引用 category_id
,试试这个:
<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>