Default order for models?

3 views
Skip to first unread message

Joe Ruby

unread,
Aug 31, 2006, 9:45:03 PM8/31/06
to rubyonra...@googlegroups.com
Is there a way to specify the default order for models? So you could
just do this:

items.find(:all).each do ...

rather than:

items.find(:all, :order=>'name').each do ...

Joe

--
Posted via http://www.ruby-forum.com/.

Jeffrey Hardy

unread,
Sep 1, 2006, 2:22:37 PM9/1/06
to rubyonra...@googlegroups.com
Hi Joe --

On 31-Aug-06, at 9:45 PM, Joe Ruby wrote:
> Is there a way to specify the default order for models?

No, there isn't.

For the sake of consistency, I think there should be -- when you're
doing associations you can specify the order there, (as in
has_many :foos, :order => 'created_at desc'), so why not a default
order for the model?

You could always override the find method in your model class,
though. Something like:

def self.find(*args)
if args.first.is_a?(Symbol)
args << {} if args.size < 2
args.last.reverse_merge! :order => "#{self.table_name}.name"
super args.first, args.last
else
super
end
end

That would give you a default order by on 'name', which could be
overridden by specifying the :order option explicitly, as per usual.

HTH

/Jeff

Chris Hall

unread,
Sep 1, 2006, 3:38:42 PM9/1/06
to rubyonra...@googlegroups.com
take a look at this article, it may be of some help for you.

http://habtm.com/articles/2006/02/22/nested-with_scope

this article basically explains various ways to utilize with_scope.
one of the methods addresses a very similar situation to yours,
however, it is done at the controller level rather than the model. it
still may be useful to you.

Chris

Reply all
Reply to author
Forward
0 new messages