jeudi 2 juin 2016

Rails: Best way to group and display a association with 3 model

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..)

Aucun commentaire:

Enregistrer un commentaire