我和这篇帖子Rails ActiveRecord sort by count of join table associations几乎有相同的情况,但我无法让它发挥作用。
我有一张名为coffeeshops
的表格,其中users
的表格可以通过名为favorite_coffeeshops
的第三个表格来收藏咖啡店。我正在使用acts_as_taggable
gem。
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 :(得分:0)
语法错误告诉您,期望)
字符关闭括号,但会转到end
语句。
如果你看这一行:
.joins(:favorite_coffeeshops.group(:favorite_coffeeshops.coffeeshop_id)
(根据您的语法错误应该是第12行),然后您可以看到有两个开放的(
字符,但只有一个关闭)
。
因此,要修复语法错误,只需在调用)
方法之前为joins
方法添加缺少的group
,即:
.joins(:favorite_coffeeshops).group(:favorite_coffeeshops.coffeeshop_id)