空关系的Activerecord查询模型

时间:2011-10-12 08:43:25

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

我有以下课程/关系:

#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')

关系查询的正确语法是什么?我可以在不使用计数器缓存的情况下有效地执行此操作吗?

1 个答案:

答案 0 :(得分:1)

在user.rb中:

scope :has_posts, :conditions => "users.id IN (SELECT user_id FROM posts)"
控制器中的

User.has_posts
相关问题