sql - Rails: ActiveRecord query is forcing ORDER BY after DISTINCT -


i using query:

post.where("created_at >= ? , created_at <= ?", 1.month.ago.beginning_of_month , 1.month.ago.end_of_month)     .select('distinct user_id') 

which returns 40 elements. however, expect array query, , able iterate on array .each. issue when try use .each on result of query, this:

activerecord::statementinvalid: pg::invalidcolumnreference: error: select distinct, order expressions must appear in select list line 1: ...ted_at <= '2016-06-30 21:59:59.999999') order created_at... ^ : select distinct user_id "posts" (created_at >= '2016-05-31 22:00:00.000000' , created_at <= '2016-06-30 21:59:59.999999') order created_at desc

it seems query forces order by on created_at, , makes break since order_by isn't in query.

to avoid issue, i'm using:

post.where("created_at >= ? , created_at <= ?", 1.month.ago.beginning_of_month , 1.month.ago.end_of_month)     .map{|p| p.user_id}.uniq 

which less efficient.

any idea why i'm getting error?

try following:

post.where(created_at: (1.month.ago.beginning_of_month)..1.month.ago.end_of_month)     .distinct.reorder(nil).pluck(:user_id) 

as mentioned in comments, due default_scope:

default_scope {order('created_at desc')} 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -