2016-08-02 114 views
0

我正在嘗試檢索21張最常瀏覽的照片的列表。我有這樣的代碼在我的控制器:Rails插入錯誤的`訂單`語句

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

,並輸出下面的SQL:

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

哪裏timestamp DESC查詢來自何處,我如何擺脫它?照片按時間順序而不是按照查看次數返回。

+0

檢查,如果任何默認範圍寫的? – Sravan

回答

3

也許您在使用Photo模型時使用了default_scope。如果是這樣的話,請嘗試使用:

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

如果你有default scope你應該使用unscoped覆蓋或刪除默認範圍。

unscoped(): Returns a scope for the model without the previously set scopes.

default_scope(scope = nil) :- Use this macro in your model to set a default scope for all operations on the model.

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

那麼查詢應該是,

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