Cbas Cbas - 2 months ago 6
SQL Question

Rails inserting incorrect `order` statement

I am trying to retrieve a list of the 21 most viewed photos. I have this code in my controller:

@photos = Photo.where("group_id = (?)", params[:target_id]).order('view_count ASC').limit(21)

and it outputs the following SQL:

SELECT "photos".* FROM "photos" WHERE group_id = ('205') ORDER BY "photos"."timestamp" DESC, view_count ASC LIMIT 21

Where is the
timestamp DESC
query coming from and how do I get rid of it? The photos are being returned chronologically instead of by view count..


Maybe you are using a default_scope in your Photo model. If that's so, try using:

@photos = Photo.unscoped.where("group_id = (?)",params[:target_id]).order('view_count ASC').limit(21)