如何“通过”使用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
,我该怎么办呢?
谢谢!
答
你需要 “:包括(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
你对Thing模型的定义缺失 – Tilo
道歉..它是页面和事物之间的关系,而不是书本,我在原文中修复了它:) – jakobk