2017-04-02 107 views
0

獲取的has_many的普及,我有以下型號&關係通過關係

Category 
    has_many :candy 
    # these are examples 
    #"Hard Candy" "Gummies" "Rock Candy" "Gum" "Jawbreakers" "Lollipops" "Licorice" "Liquid Candy" "Powder Candy" "Taffy" 

CandyCategory 
    belongs_to :candy 
    belongs_to :category 

Candy 
    has_many :candy_categories 
    # Examples "Lemon Drop", "Tootsie Rolls", "Blow Pop", "Ring Pop", "Fun Dip" 

Likes 
    belongs_to :user 
    belongs_to :candy 
    has_many :categories, through: :candy 
    # there is some meta data here, but the important bits are just the relationships 

我試圖推導基於糖果本身的喜歡最流行的類別名稱。

我可以按類別名稱進行分組,並獲得一個計數,但是(顯然)不會給我帶類別對象,只是一個名稱和計數的數組。

例如

Like.includes(:categories).references(:categories).group("categories.name").count 

能有人能管管我今天告訴我的我的ActiveRecordee方式錯誤!?!在一天結束時,我需要一個Category對象列表,或者至少是類別名稱和ID。

回答

0

EUREKA !!!!

所以,顯然我對這件事感到很興奮,這並不難,我只是在想它。

這裏的解決方案:

Category.joins(:candy).includes(:likes).group(:categories).count