Reputation: 6906
I have two models in my app, one called Feed
and one called Post
. A feed has many posts.
I am looking for a way to return the feeds where the most recent post is older than 1 month.
I've got something simple like:
class Feed < ActiveRecord::Base
has_many :posts
scope :no_recent_posts, -> { includes(:posts).where('posts.created_at > ?', 1.month.ago) }
end
but of course this also returns any feeds if they have old posts (even if they have more recent ones too.
Maybe something with a limit(1
) and an order
?
Upvotes: 0
Views: 330
Reputation: 15056
You can achieve this with a GROUP BY...HAVING
.
scope :no_recent_posts, { joins(:posts).group(:feed_id).having('max(posts.created_at) > ?', 1.month.ago)
Since you don't really need to eager load the posts (based on your requirements), I changed the includes
to a joins
.
Upvotes: 2