user7067399 user7067399 - 1 month ago 7
Ruby Question

select posts from one day

I want to select posts from one day. What is the correct way? This errors:

date = '3/11/2016'.to_date

User.joins(:posts).where(posts: {'created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day})

Answer
Posts.where('created_at >= ? and created_at <= ?', Date.today.at_beginning_of_month, Date.today)

There is no need to join User unless you want the user as well then you could do this

User.joins(:posts).all.where('posts.created_at >= ? and posts.created_at <= ?', Date.today.at_beginning_of_month, Date.today).preload(:posts)

The preload will help with efficiency

Comments