ruby on rails - ActiveRecord querying since date X -
i have post
, acomment
model. i'm trying retrieve posts have comments, not have comments since date x.
@posts = post.all.includes(:comments).where('comments.created_at < ?', 1.month.ago)
this query retrieves posts comments before date x, not ensure there no comments since date x.
a improve approach querying lastly comment each post , comparing against date x. possible in 1 query?
the next query looks bit long , complicated, way come result looking for. homecoming posts have comments not more recent 1 month ago, , there no comments same post since 6 months ago:
@posts = post.all.joins(:comments).where('comments.created_at < ?', 1.months.ago).where('not exists (select * comments created_at > ? , post_id = posts.id)',6.months.ago).references(:comments)
it produce next sql query:
select "posts".* "posts" inner bring together "comments" on "comments"."post_id" = "posts"."id" (comments.created_at < '2014-09-24') , (not exists (select * comments created_at > '2014-04-24' , post_id = posts.id))
according tests should homecoming result looking for.
ruby-on-rails activerecord
No comments:
Post a Comment