jakobk
jakobk

Reputation: 1132

How to "order by" using has_many through?

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
    end


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

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

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

Thanks!

Upvotes: 1

Views: 910

Answers (1)

Tilo
Tilo

Reputation: 33752

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)

See:

http://guides.rubyonrails.org/active_record_querying.html

http://m.onkey.org/active-record-query-interface

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Upvotes: 2

Related Questions