Rails插入错误的`order`语句

时间:2016-08-02 04:39:32

标签: mysql ruby-on-rails

我正在尝试检索21张查看次数最多的照片。我的控制器中有这个代码:

@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查询来自何处以及如何摆脱它?这些照片按时间顺序返回,而不是按照观看次数返回。

2 个答案:

答案 0 :(得分:3)

也许您在String value = DummyStatic.arl_static.get(position).edt_field; 模型中使用了default_scope。如果是这样,请尝试使用:

Photo

答案 1 :(得分: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