ActiveRecord conditions of an association (Rails)
-
05-07-2019 - |
Question
Pretend I have a model, Post which has_many :comments. How can I only display posts that have comments?
I am somewhat comfortable with named_scope but I don't know how I can put Post.comments (or self.comments) in the :conditions hash which expects symbols.
class Post < ActiveRecord::Base
has_many :comments
named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
What do I write in the commented area?
Thanks!
Solution
Better might be to put a counter_cache on Post.
class Comment < AR:Base
belongs_to :post, :counter_cache => true
end
Then you only need to do 1 query instead of two.
Post.find(:all, :conditions => ["counter_cache > 0"])
OTHER TIPS
You should be able to just join against your comments table, making sure to select the distinct rows
named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow