我有以下课程/关系:
#post.rb
belongs_to :user
#user.rb
has_many :posts
我需要做这样的事情:
scope :has_posts, joins(:posts).where('posts is not empty')
或类似的东西:
User.where('posts is not empty')
关系查询的正确语法是什么?我可以在不使用计数器缓存的情况下有效地执行此操作吗?
答案 0 :(得分:1)
在user.rb中:
scope :has_posts, :conditions => "users.id IN (SELECT user_id FROM posts)"
控制器中的:
User.has_posts