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