I have 3 model: Place, Service, ItemService and 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. example.
Table 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
+----+-------+-------------+
| 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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.