我有一个包含所有Address
集合的选择字段。我希望将"address.name / country.name"
显示为值。
= item.collection_select :address_id, Address.all, :id, :name
目前在此示例中,我只显示address.name
属性。如何在此处嵌套其他值以及如何从嵌套关联中调用值? (address.country.name
)。 ?
通过做这样的事情我得到了它。只是想知道是否有更好的东西。
%select{name: "user[address_id]"}
- Address.all.each do |address|
%option{value: address.id}
= address.name
= address.country.name
答案 0 :(得分:1)
试试这个:
= item.collection_select :country_id, Address.all, :id, :full_address
比为模型添加方法:
def full_address
full_address = name
full_address += " / #{country.name}" if country.present?
full_address
end
答案 1 :(得分:1)
您可以在Address模型上编写自己的方法,它将为集合选择一个很好的名称:
class Address < ActiveRecord::Base
def name_with_country
str = self.name
str += " #{self.country.name}" if self.country.present?
str
end
并在collection_select中使用它:
= item.collection_select :address_id, Address.all, :id, :name_with_country