2017-06-14 30 views
0

我和這篇文章Rails ActiveRecord sort by count of join table associations有幾乎相同的場景,但我無法完全實現它。在Rails 5中對連接表進行計數和排序

我有一個名爲coffeeshops的表格,其中users的表格可以通過稱爲favorite_coffeeshops的第三個表格來喜愛咖啡店。我正在使用acts_as_taggable寶石。

class Coffeeshop < ApplicationRecord 
    has_many :favorite_coffeeshops# just the 'relationships' 
    has_many :favorited_by, through: :favorite_coffeeshops, source: :user 

class FavoriteCoffeeshop < ApplicationRecord 
    belongs_to :coffeeshop 
    belongs_to :user 

class User < ApplicationRecord 
    has_many :coffeeshops 
    has_many :favorite_coffeeshops # just the 'relationships' 
    has_many :favorites, through: :favorite_coffeeshops, source: :coffeeshop 

在我的控制,我有以下:

def index 
.... 

@favshops = Coffeeshop.select 
('coffeeshops.*, count(favorite_coffeeshops.coffeeshop_id) as favorite_coffeeshops_count') 
.joins(:favorite_coffeeshops.group(:favorite_coffeeshops.coffeeshop_id) 
.order('favorite_coffeeshops DESC') 
end 

實際上我得到一個語法錯誤,之前我甚至可以檢查查詢是否正確。這是否與跨多行包裝字符串有關?

SyntaxError (/Users/Simon/gourmet_coffee/app/controllers/home_controller.rb:12: syntax error, unexpected keyword_end, expecting ')' 
    end 
    ^
/Users/Simon/gourmet_coffee/app/controllers/home_controller.rb:17: syntax error, unexpected end-of-input, expecting keyword_end): 

回答

0

的語法錯誤是告訴你,這是期待)字符關閉一個括號,但達成end語句。

如果你看一下這行:

.joins(:favorite_coffeeshops.group(:favorite_coffeeshops.coffeeshop_id)

,那麼你就可以看到有兩個開放(字符,但只有一個閉合)(這要根據你的語法錯誤是第12行) 。

所以解決你只需要添加缺少的)joins方法的語法錯誤,被稱爲group方法之前,即:

.joins(:favorite_coffeeshops).group(:favorite_coffeeshops.coffeeshop_id)

相關問題