2017-06-14 84 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)