关于 ActiveRecord#default_scope 方法和默认排序的问题 [英] Question about ActiveRecord#default_scope method and default ordering

查看:50
本文介绍了关于 ActiveRecord#default_scope 方法和默认排序的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用 Rails 2/3 的 default_scope 的问题.在我的 Rails 3 项目中,我使用了很多 default_scope 来通过 created_at desc 进行排序.所以首先我写道:

<前>default_scope order("created_at desc")

在我的许多模型中.但问题是 created_at 几乎存在于我的每个应用程序表中......因此,如果我编写一个简单地对两个表进行连接的查询,我会收到一个 SQL 错误 ambiguous column created_at...所以我不得不重写所有 default_scopes 以包含 table_name,例如:

<前>default_scope order("posts.created_at desc")

有没有更好的方法来处理这个问题,还是唯一的解决方案?

谢谢.

解决方案

在 Rails 中使用 SQL 字符串时,应始终指定表名,以避免这些歧义.请注意,您可以这样做:

default_scope order("#{table_name}.created_at desc")

Question about default_scope with Rails 2/3. On my Rails 3 project, I'm using a lot default_scope to order by created_at desc. So first I wrote :

default_scope order("created_at desc")

in many of my models. But the problem is that created_at exist in almost every of my application tables... So if I write a query that simply makes a join on two tables, I get a SQL error ambiguous column created_at... So I had to rewrite all default_scopes to include the table_name, like:

default_scope order("posts.created_at desc")

Is there a better way to handle this problem or is it the only solution?

Thanks.

解决方案

You should always specify the table name when using SQL strings in Rails so that you avoid these ambiguities. Note that you can do:

default_scope order("#{table_name}.created_at desc")

这篇关于关于 ActiveRecord#default_scope 方法和默认排序的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆