has_many 和belongs_to 关联的单选按钮 [英] Radio buttons for a has_many and belongs_to association
问题描述
我有一个has_many 和belongs_to 关联.
I have a has_many and belongs_to association.
class Link < ActiveRecord::Base
has_and_belongs_to_many :categories
belongs_to :property
end
class Property < ActiveRecord::Base
has_many :links
end
在索引和显示中我有 <%= link.property.name %>
它将显示我分配给带有控制台的链接的属性就好了.
In the index and show I have <%= link.property.name %>
and it will show the Property that I assigned to the link with the console just fine.
我在弄清楚如何在 _form 中显示为链接分配属性的单选按钮时遇到问题(下拉菜单也可以).
I have a problem with figuring out how to show radio buttons in the _form that assign a property to the link (a drop down would work as well).
似乎之前遇到过这个问题的每个人都有一个 has_many :through 或 HABTM 关系,我似乎无法调整他们的答案.
It seems everyone who has had this question before has ether a has_many :through or a HABTM relationship and I can't seem to adapt their answers.
推荐答案
由于每个链接只有一个属性,您可能需要单选按钮(而不是复选框).这应该有效(在您看来)
Since each link has only one property, you probably want radio buttons (not check boxes). This should work (in your view)
<%= form_for @link do |f| %>
<% @properties.each do |p| %>
<%= f.radio_button :property_id, p.id %>
<%= f.label :property_id, p.name %>
<% end %>
<%= f.submit %>
<% end %>
不要忘记在控制器中设置 @properties = Property.all
.
Don't forget to set @properties = Property.all
in your controller.
这篇关于has_many 和belongs_to 关联的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!