I'm trying to figure out a way to order a model's collection based on an attribute of an association of the collected model (I think... what a mouthful). Here's what I'm doing:
class Item < ActiveRecord::Base
belongs_to :category
end
class Order < ActiveRecord::Base
has_many :items, :order => :category_id
end
At the moment order.items
returns the Items ordered by the category_id. But what I really want is to have them listed by alphabetical category.name
. Is that possible?
Thanks, Stewart
It should work if you use :include to eager load the categories.
class Order < ActiveRecord::Base
has_many :items, :include => :categories, :order => "categories.name"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With