Tuesday, 1 October 2013

How do you sort a collection by distant relationships?

How do you sort a collection by distant relationships?

I have a tree-like relationship model with a fixed depth, and each level
has a code attribute - similar to this;
class Category < ActiveRecord::Base
has_many :sub_categories
default_scope order(:code)
end
class SubCategory < ActiveRecord::Base
belongs_to :category
has_many :items
def self.sorted
self.joins(:category).order('"categories".code ASC,
"sub_categories".code')
end
end
class Item < ActiveRecord::Base
belongs_to :sub_category
def self.sorted
# what goes here?
end
end
Category.all gets all the the categories ordered by categories.code.
SubCategory.sorted gets all the sub_categories ordered by categories.code,
sub_categories.code. I used this approach because default_scope :
joins(:categories).order('categories.code, sub_categories.code') makes
.find return read-only records.
I would like to call Items.sorted and get the all items ordered by
categories.code, sub_categories.code, items.code but I can't figure out
how. I imagine I need a second .joins, but I don't have a relationship
name to supply.

No comments:

Post a Comment