开发者

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 (ha开发者_Go百科s_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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜