Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails order collection by attribute of associated model?

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

like image 617
Stewart Johnson Avatar asked Sep 11 '11 06:09

Stewart Johnson


Video Answer


1 Answers

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
like image 135
spike Avatar answered Nov 08 '22 23:11

spike