2017-02-22 59 views
0

我有這個產業鏈的模式:Rails - 如何與許多模型group_by?

enter image description here

而且我有suboptions列表。我想group_by每個上述父親的子選項。

因此,它將被劃分爲分類,這將分爲活動,這將分爲選項。你有看到?

我該怎麼做?

Suboptions.all.group_by(???) 
# or 
Suboptions.all.order_by(????) 
# or ???? 

實施例:

子選項

+----+-----------+ 
| id | option_id | 
+----+-----------+ 
| 1 |   1 | 
| 2 |   2 | 
| 3 |   2 | 
| 4 |   4 | 
| 5 |   3 | 
+----+-----------+ 

選項

+----+-------------+ 
| id | activity_id | 
+----+-------------+ 
| 1 |   1 | 
| 2 |   2 | 
| 3 |   1 | 
| 4 |   3 | 
+----+-------------+ 

活動

+----+-------------+ 
| id | category_id | 
+----+-------------+ 
| 1 |   1 | 
| 2 |   2 | 
| 3 |   1 | 
+----+-------------+ 

分類

+----+------+ 
| id | name | 
+----+------+ 
| 1 | cat1 | 
| 2 | cat2 | 
+----+------+ 

那麼搜索應該返回與ID的子選項按以下順序:[1,5,4,2,3] (試着想象它從類別到子選項)

+0

sql中的GROUP BY是爲了按給定條件對選定記錄進行分組,然後返回每個組的第一個記錄。這是你想要的嗎? https://www.tutorialspoint.com/postgresql/postgresql_group_by.htm – nicooga

+2

您能否提供樣本輸入和預期輸出? – siopao

+0

@nicooga我剛剛意識到我實際需要的是'order_by' .. –

回答

2

根據數據集的大小,聽起來就像你想要做一個連接,然後命令

Suboption.joins(option: {activity: :category}).order('categories.name') 

這是否適合您?

+0

差不多吧!我加入了所有表格,然後通過它們的ID(category_id,activity_id,option_id和suboption_id)對它們進行排序。 –