making ActiveRecord::Base sort by id

24 views
Skip to first unread message

Ruby Railhead

unread,
Jun 10, 2015, 2:56:59 PM6/10/15
to rubyonra...@googlegroups.com
Hello, 

I'm trying to mix in a module so that AR::Base will sort all record by ID by default. 

 I've worked up a repo with a few methods of doing things similar to this, but I can't get this working as I want (I started with the rails project from https://www.digitalocean.com/community/tutorials/how-to-setup-ruby-on-rails-with-postgres )

There are three non-master branches on that project:

   - is close but doesn't work. This is close to what I want to get working. Can anyone help me get this branch working?

     - works but introduces an intermediate subclass

    - puts the 'order by' directly in the mode. Works but requires change to each subclass.

Again, can anyone help me to make the changes to get the branch at 
Working?

Thanks very much in advance,
 Ruby

Colin Law

unread,
Jun 10, 2015, 3:03:12 PM6/10/15
to rubyonra...@googlegroups.com
On 10 June 2015 at 19:56, Ruby Railhead <rubyra...@gmail.com> wrote:
> Hello,
>
> I'm trying to mix in a module so that AR::Base will sort all record by ID by
> default.

Can I ask why you would want to do that? You don't have to give a
reason of course, just interested.

Colin

javinto

unread,
Jun 11, 2015, 4:29:19 AM6/11/15
to rubyonra...@googlegroups.com
I would not recommend using a default scope on an ActiveRecord model for sorting.

Start your Rails console and try Model.find(1). This will result into: SELECT models.* FROM models WHERE models.id=1 ORDER BY id DESC LIMIT 1

This ORDER BY will be included in every unneccessary query. The above query will be slower in MySQL than without the ORDER BY clause. Try it yourself!

Create a normal scope and include it with every query where you expect more than 1 record as a result.

In case you consider a mixin try http://api.rubyonrails.org/classes/ActiveSupport/Concern.html


Reply all
Reply to author
Forward
0 new messages