Take the 2-minute tour ×

I have two tables with a join table between them:

Parent: Pages
Child: Things
Join: Grids

In my models they are set up with a many to many relationship (has_many through):

   class Page < ActiveRecord::Base
      belongs_to :books
      has_many :grids
      has_many :things, :through => :grids

class Thing < ActiveRecord::Base
      has_many :grids
      has_many :pages, :through => :grids

    class Grid < ActiveRecord::Base
      belongs_to :page
      belongs_to :thing

Now I want to be able to sort "things" using an ordering id from grid, called number, how can I do that ?


share|improve this question
your definition of the Thing model is missing –  Tilo Oct 8 '11 at 13:13
Apologies.. it's the relationship between page and things, not the book, I fixed it in the original post : ) –  jakobk Oct 8 '11 at 14:43
add comment

1 Answer

up vote 2 down vote accepted

you need the ":include(s)" option in your find method, and then "order_by()" ...

you would use something like this:

Thing.where(...some condition or all..., :include => :grid ).order_by(grid.number)





share|improve this answer
Should that be has_many :pages, :through => :things? –  mliebelt Oct 8 '11 at 14:16
And is that ...order_by(grid.number) valid? What is that grid in that context? Should it be ...order_by('grid.number')? –  mliebelt Oct 8 '11 at 14:21
Thanks! - It worked except it's ".order(grids.number)" Also great links, just what I've been looking for .. –  jakobk Oct 8 '11 at 14:42
add comment

Your Answer


