[英]Rails: Best way to group and display a association with 3 model
I have 3 model: Place, Service, ItemService and ItemServicesProduction. 我有3个模型:Place,Service,ItemService和ItemServicesProduction。
class Place < ActiveRecord::Base
has_many :item_services, through: :place_item_services
has_many :place_item_services
end
class Service < ActiveRecord::Base
has_many: item_services
end
class ItemService < ActiveRecord::Base
belongs_to :service
end
I want to show place with item_services group by Service. 我想按服务显示item_services组的位置。 example.
例。
Table place_item_services 表place_item_services
+----+----------+------------------+---------------------+---------------------+
| id | place_id | item_service_id | created_at | updated_at |
+----+----------+------------------+---------------------+---------------------+
| 1 | 5 | 1 | 2016-05-16 12:31:59 | 2016-05-16 12:31:59 |
| 2 | 5 | 2 | 2016-05-16 12:31:59 | 2016-05-16 12:31:59 |
| 3 | 6 | 2 | 2016-05-21 07:58:19 | 2016-05-21 07:58:19 |
| 4 | 5 | 5 | 2016-06-02 08:32:24 | 2016-06-02 08:32:24 |
| 5 | 5 | 6 | 2016-06-02 08:32:24 | 2016-06-02 08:32:24 |
+----+----------+------------------+---------------------+---------------------+
table Service 餐桌服务
+----+-----------+
| id | name |
+----+-----------+
| 1 | service 1 |
| 2 | service 2 |
+----+-----------+
table item_services 表item_services
+----+-------+-------------+
| id | name | facility_id |
+----+-------+-------------+
| 1 | sv1-1 | 1 |
| 2 | sv1-2 | 1 |
| 3 | sv1-3 | 1 |
| 4 | sv2-1 | 2 |
| 5 | sv2-2 | 2 |
| 6 | sv2-3 | 2 |
+----+------ +-------------+
When i show place in View (with place id = 5) i want to display 当我在View中显示地点(地点ID = 5)时,我想显示
Place_Name
/*Service is here*/
1. service 1
- sv1-1
- sv1-2
2. service 2
- sv2-2
- sv2-3
The best way how to display same above? 最好的方法如何在上面显示相同? (can use inclues, joins, group by .etc..)
(可以使用包含,加入,分组等。)
your controller 您的控制器
@place = Place.find(5)
@services = Services.includes({item_services: :place_item_services}).where(place_item_services: {place_id: @place.id})
your view 你的看法
<p>Place: <%= @place.name %></p>
<ol>
<% @services.each do |service| %>
<li>
<ul>
<% service.item_services.each do |item_service| %>
<li><%= item_service.name %></li>
<% end %>
</ul>
</li>
<% end %>
</ol>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.