Forum: Ruby on Rails Dynamic order on has_many relationship?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
8fd9f26b8f23d49c8a89b63f1279e24f?d=identicon&s=25 Chris (Guest)
on 2005-12-26 08:14
(Received via mailing list)
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?


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

class Category < AR:B
	has_many :products, :order => "product_id"
	has_many :products_by_desc, :class_name => "Product", :order =>
	has_many :products_by_gtin, :class_name => "Product", :order => "gtin"

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?

443a308e12ba2a3082fb6170ca94c2ef?d=identicon&s=25 Ed Wg (ewildgoose)
on 2005-12-26 10:35
(Received via mailing list)
Chris 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

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
821395fe70906c8290df7f18ac4ac6cf?d=identicon&s=25 Rick Olson (Guest)
on 2005-12-26 16:25
(Received via mailing list)
> 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')

This topic is locked and can not be replied to.