2011-10-12 20 views
0

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
在user.rb

scope :has_posts, :conditions => "users.id IN (SELECT user_id FROM posts)" 

在控制器:

User.has_posts