Rails Active Record计数关联

时间:2017-05-15 22:47:30

标签: sql ruby-on-rails ruby sqlite activerecord

我一直在尝试在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中帖子的收藏数,但它在这里不起作用......

谢谢,

2 个答案:

答案 0 :(得分:0)

此错误表示SQLite不能favorite_count阻止order by列。如果您以明确的方式重写order by favorite_count

Post.
  joins('INNER JOIN favorites ON posts.id = favorites.favorited_id').
  select('posts.*, COUNT(favorites.favorited_id) AS favorite_count').
  group('posts.id').
  order('COUNT(favorites.favorited_id) desc').limit(10)

答案 1 :(得分:0)

我继续使用这个添加了专栏:ryan.mcgeary.org/2016/02/05 / ...并且它工作得非常好,我可以致电:Post.unscoped.order('posts.favorites_count desc').limit(10)