Hi,
this is a general design question and I liked to see how other people
handle the following situation: Before named_scope I wrote custom
finders for my model classes. Something like
order.rb
class Order < ActiveRecord::Base
class << self
def find_all_marked
find(:all, :conditions => {:marked => 1}, :order => ‘name ASC’)
end
end
end
Now this can easily be refactored to
class Order < ActiveRecord::Base
named_scope :marked, :conditions => {:marked => 1}, :order => ‘name
ASC’
end
While the find_all_marked method (to me) felt simple enough to include
an :order option, the same thing just feels wrong in the named_scope.
I mean I knew exactly where I would be calling that method from, but
named scopes can be combined and are very flexible. Especially they do
not behave very intuitively when combining two names scopes that
include an :order option:
order.rb
named_scope :active, :condtitions => …, :order => ‘created_at DESC’
Order.marked.active # ordered by ‘name ASC’ according to the first
scope ‘marked’
So what are the options?
orders_controller.rb
def index
@marked = Order.marked.find(:all, :order => ‘name ASC’)
end
No, that feels like bleeding model code into the controller.
order.rb
named_scope :ordered_by_name, :order => ‘name ASC’
orders_controller.rb
@marked = Order.marked.ordered_by_name
Still my best idea yet, but also quite verbose. It would be nice if
you could define a default order for a named_scope and then you could
use ‘ordered_by_’-scopes to override. But the naive approach fails
here, because the order of the first scope takes priority over any
following.
How do you handle this situation?
Regards,
Tim