嵌套资源/控制器/视图

时间:2011-11-11 11:13:00

标签: ruby-on-rails ruby-on-rails-3

公寓管制员:

@appartment = Appartment.find(params[:id])
@amenities = @appartment.amenities

模特公寓:

has_many :amenity_appartment
has_many :amenities, :through => :amenity_appartment

模型舒适性

has_many :amenity_appartment
has_many :appartments, :through => :amenity_appartment
belongs_to :category_amenity

Model CategoryAmenity

has_many :amenities

为了展示公寓的设施,我有这个:

<% @amenities.each do |amenity| %>
    <p><%= amenity.name %></p>

我得到了所有设施的清单,但我可以将其与category_amenity的名称分开吗?

1 个答案:

答案 0 :(得分:2)

您应该先在控制器中按类别对设施进行分类:

@amenities = {}
@appartment.amenities.each do |a|
  @amenities[a.category_amenity.name] ||= []
  @amenities[a.category_amenity.name] << a
end

并向他们展示:

<% @amenities.each do |category_name, vals| %>
    <p><%= category_name %></p>
    <% vals.each do |amenity| %>
      ....