簡體   English   中英

Rails:分組和顯示與3模型的關聯的最佳方法

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

我有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

我想按服務顯示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 |
+----+----------+------------------+---------------------+---------------------+

餐桌服務

+----+-----------+
| id | name      |
+----+-----------+
|  1 | service 1 |
|  2 | service 2 |
+----+-----------+

表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 |
+----+------ +-------------+

當我在View中顯示地點(地點ID = 5)時,我想顯示

Place_Name
/*Service is here*/

 1. service 1
    - sv1-1
    - sv1-2
 2. service 2
    - sv2-2
    - sv2-3

最好的方法如何在上面顯示相同? (可以使用包含,加入,分組等。)

您的控制器

@place    = Place.find(5)
@services = Services.includes({item_services: :place_item_services}).where(place_item_services: {place_id: @place.id})

你的看法

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM