如何“通过”使用has_many通过?

问题描述:

我和他们之间的连接表两张表:如何“通过”使用has_many通过?

家长:页
儿童:事情
加入:编制

在我的模型,他们是通过建立一个多对多的关系(的has_many ):

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 

现在我希望能够以“事”使用来自电网的订单ID进行排序,称为number,我该怎么办呢?

谢谢!

+0

你对Thing模型的定义缺失 – Tilo

+0

道歉..它是页面和事物之间的关系,而不是书本,我在原文中修复了它:) – jakobk

你需要 “:包括(S)”,在您的查找方法选项,然后 “ORDER_BY()” ......

你会使用这样的:

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

参见:

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

应该是'has_many:pages,:through = >:事情? – mliebelt

+0

那是'... order_by(grid.number)'有效吗?在这种情况下,“网格”是什么?它应该是...... ... order_by('grid.number')'? – mliebelt

+0

谢谢! - 它的工作原理除了“.order(grids.number)”还有很棒的链接,就是我一直在寻找的东西.. – jakobk