我和这篇文章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):