Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 869
user385029 Avatar asked Jul 23 '10 12:07

user385029


People also ask

Is ActiveRecord a framework?

1.3 Active Record as an ORM Framework Represent inheritance hierarchies through related models. Validate models before they get persisted to the database. Perform database operations in an object-oriented fashion.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is ActiveRecord implementation?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database.


1 Answers

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")
like image 112
John Topley Avatar answered Sep 20 '22 01:09

John Topley