1

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})

3 Answers3

1
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

C dot StrifeVII
  • 1,885
  • 1
  • 16
  • 21
0

If you are just trying to select by day you might try something like this.

User.joins(:posts).where(posts: { 'extract(day from created_at) = ?', desired_day_of_month } )

Dan
  • 1,238
  • 2
  • 17
  • 32
0

you have an issue with the syntax:

posts: {'created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day}

the hash syntax should be used to send the columns to query, such as:

posts: { title: 'some title' }, etc

In your case, you should do:

User.joins(:posts).where('posts.created_at >= ? AND posts.created_at <= ?', date.beginning_of_day, date.end_of_day)
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81