我写这个是为了计算唯一用户的回复(对帖子)的数量:
p = Post.find 1
r = p.responses.count(:user_id, distinct: true)
我尝试将其转换为范围,但会引发错误:undefined method 'default_scoped?' for 30:Fixnum
class Response < ActiveRecord::Base
belongs_to :author, class_name: 'User', foreign_key: 'user_id'
belongs_to :post
scope :by_unique_users, joins(:post).count(:user_id, distinct: true)
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :responses
end
class User < ActiveRecord::Base
has_many :posts
has_many :responses
end