【发布时间】:2017-10-14 20:31:47
【问题描述】:
我一直在尝试所有可以在 Rails 指南和此处找到的方法,按两个模型之间的关联数进行计数和排序。
控制器中的查询:
def top_mires
@title = "Top Posts"
@posts = Post.joins('INNER JOIN favorites ON posts.id = favorites.favorited_id').select('posts.*, COUNT(favorites.favorited_id) AS favorite_count').group('posts.id').order('favorite_count desc').limit(10)
render 'favorite_posts/show'
end
模型:
帖子:
class Post < ApplicationRecord
include PublicActivity::Common
acts_as_taggable
belongs_to :user
has_many :comments
has_many :favorites, as: :favorited
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :user_id, presence: true
validates :post_type, presence: true
validates :content, presence: true
最喜欢的:
class Favorite < ApplicationRecord
include PublicActivity::Model
tracked only: [:create], owner: :user, recipient: :favorited
belongs_to :favorited, polymorphic: true, counter_cache: :favorite_count
belongs_to :user
end
但我得到了这个错误:
SQLite3::SQLException: no such column: favorite_count: SELECT COUNT(*) AS count_all, posts.id AS posts_id FROM "posts" INNER JOIN favorites ON posts.id = favorites.favorited_id GROUP BY posts.id ORDER BY "posts"."created_at" DESC, favorite_count desc LIMIT ?
Favorites.count 怎么不是列?我也多次使用 posts.favorites.count 来显示 ERB 中帖子的收藏计数,但它在这里不起作用......
谢谢你,
【问题讨论】:
标签: sql ruby-on-rails ruby sqlite activerecord