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