开发者

Question about ActiveRecord#default_scope method and default ordering

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 probl开发者_开发百科em 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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜