Forum: Ruby on Rails Set default order for find(:all) in a model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel -. (Guest)
on 2005-11-25 09:01
(Received via mailing list)
Hi everyone

Is there a way that I can get the find(:all) method to return in a
specified
order, without including the :order argument every time?

Guess I just don't like typing...

Cheers
Christer N. (Guest)
on 2005-11-25 11:25
You could always define your own subroutine :-)
Chris G. (Guest)
on 2005-11-25 11:32
liquid wrote:
> Is there a way that I can get the find(:all) method to return in a
> specified order, without including the :order argument every time?

A default table order sounds like a MySQL thing. You can specify an
order for your associations though:

    has_many :velvet_elvis_posters, :order => 'velvetiness desc'

> Guess I just don't like typing...

This is a good thing. If it weren't for people like you, we'd still be
using Java. :)
dom (Guest)
on 2005-11-25 11:47
(Received via mailing list)
On Friday 25 November 2005 07:01, Liquid wrote:
> Hi everyone
>
> Is there a way that I can get the find(:all) method to return in a
> specified order, without including the :order argument every time?

1.
Override the find method in that model?

or

2.
class Foo < ActiveRecord::Base
  ...
  def my_find
    find(:all, ...)
  end
  ...
end

Then use my_find where you would have used find.

My non-expert opinion is that 2. is slightly better than 1. because you
may at some point need another version of find sorted differently and
you may make life more difficult by modifying the default behaviour of
find rather than adding a new version with its own behaviour.

> Guess I just don't like typing...
>
> Cheers

HTH,
Daniel -. (Guest)
on 2005-11-25 11:59
(Received via mailing list)
Thanx for the suggestions guys..

I have thought of trying to extend ActiveRecord..  I'm not completely
sure
how to do that yet.  What I've been thinking of is to overwrite the find
method, and if there is no :order argument defined, I would like to put
an
instance or class variable in my model, that I include as the :order
argument

eg

class SomeModel < ActionRecord
 @@order = 'the_order_field, another_field'
....

end

Then whenever the find method is called.  If there is no :order
specified,
order by @@order.  If there is no @@order specified just execute the
original find...

The reason for this is because I'm trying to use an engine, but I want
to
specify what order the lists are presented without going into that code
at
all.

Any help would be great.

Cheers
This topic is locked and can not be replied to.