Dynamic order on has_many relationship?


#1

I was wondering if it’s possible to some how control the :order given
on a has_many depending on another attribute?

Or do I need to just create multiple has_many relationships pointing
to the same table but with different orders and then select which one
I use in the controller instead?

e.g

class Category < AR::B
has_many :products, :order => //something magical?//
end

class Category < AR:B
has_many :products, :order => “product_id”
has_many :products_by_desc, :class_name => “Product”, :order =>
“description”
has_many :products_by_gtin, :class_name => “Product”, :order => “gtin”
end

If I had a column that was default_order on the Category, could it
evaluate it and set the :order at the model level, or do I go in and
get my record set and hardcode which relationship matches which value
of the column?

Thanks,
Chris Nolan.ca
http://kekova.ca/


#2

Chris Nolan.ca wrote:

I was wondering if it’s possible to some how control the :order given
on a has_many depending on another attribute?

I have been wondering about the same. It did occur to me that when you
are using a has_many you aren’t really enforcing some relationship so
much as adding a convenience finder method. So it is probably just as
valid to create some function which runs find_by_sql and returns the
results you are after? There are some convenience methods added as a
result of has_many, so you may want to check you don’t rely on those.

Local sorting of your object is probably also possible (or can be
emulated)

In my case I wanted to have subsets of the has_many relation, eg find
all completed orders, find all orders, find orders not yet shipped, etc,
etc. Grateful for any better suggestions on doing this than just adding
methods to the model which return the appropriate results?

Ed W


#3

class Category < AR::B
has_many :products
end

The reason you can’t put anything in the has_many() method call is
it’s executed when the class is loaded. Luckily you can use the full
power of the find() method.

@category.products.find(:all, :order => ‘something magical’)


rick
http://techno-weenie.net