简体   繁体   English

Rails 订购方法; 列名为:顺序

[英]Rails order method; column named :order

I have a model Exercises and it has columns of:circuit and:order (among others).我有一个模型 Exercises,它有列:circuit 和:order(等等)。 In a view, I am trying to order the Exercises first by:circuit and then by:order.在一个视图中,我试图先按:circuit 然后按:order 对练习进行排序。 When I use the following:当我使用以下内容时:

@schedule.exercises.order(:circuit).each do |exercise|

it works as expected.它按预期工作。 However, when I try to add the:order column:但是,当我尝试添加:order 列时:

@schedule.exercises.order(:circuit, :order).each do |exercise|

I get the following error:我收到以下错误:

SQLite3::SQLException: near "order": syntax error: SELECT "exercises".* FROM "exercises"  WHERE "exercises"."schedule_id" = 1 ORDER BY circuit, order

The same error also occurs when I pass the:order column alone:当我单独传递 :order 列时,也会出现同样的错误:

@schedule.exercises.order(:order).each do |exercise|

SQLite3::SQLException: near "order": syntax error: SELECT "exercises".* FROM "exercises"  WHERE "exercises"."schedule_id" = 1 ORDER BY order

I'm assuming that this is because the column name (:order) is the same as the SQL method name ( order ).我假设这是因为列名 (:order) 与 SQL 方法名 ( order ) 相同。 I'm wondering if there's any way around this other than changing my column heading?我想知道除了更改我的列标题之外是否还有其他解决方法?

Thanks, Stuart谢谢,斯图尔特

Changing the column name is the only sensible option out of this.更改列名是其中唯一明智的选择。 Change it to something like "position".将其更改为“位置”之类的内容。

If you really want to try and do this you could write a find by sql query and escape the col name with back quotes like如果你真的想尝试这样做,你可以通过 sql 查询编写一个查找并使用反引号转义 col 名称,例如

ModelName.find_by_sql(SELECT * FROM ModelName ORDER BY '`order`')

But I would say you should just change the column name但我会说你应该只更改列名

I am also facing same issue, but specifying table name in order clause it works.我也面临同样的问题,但在 order 子句中指定表名是可行的。

@schedule.exercises.order("exercises.circuit ASC, exercises.order ASC").each do |exercise|

Just use "reorder" instead of "order"只需使用“重新订购”而不是“订购”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM