我知道 Rails 不支持嵌套的 has_many :through 关系,尽管早在 Rails 2 中就已经有关于补丁的讨论和开放票证。
我确实来了跨插件 https://github.com/ianwhite/nested_has_many_through这非常流畅,但是主分支不能与 Rails 3 一起使用,而且我对于是否将其用于应用程序中的关键任务任务犹豫不决,因此最近缺乏活跃的开发。那么——处理这些关系的最佳方式是什么?
class Author < ActiveRecord::Base
has_many :contracts
has_many :products, :through => :contracts
class Product < ActiveRecord::Base
has_many :contracts
has_many :orders
has_many :authors, :through => :contracts
class Contracts < ActiveRecord::Base
belongs_to :author
belongs_to :product
因此,如果能够通过将其添加到 Author 模型来获得订单,那就太棒了:
has_many :orders, :through => :products
但可惜的是,你不能——至少没有插件。所以,我的问题是,当唯一的关联存在于连接模型和合同之间时,访问所有作者订单的最佳方法是什么?
如果您不尝试通过嵌套关联创建对象,而只想将其用于查找,那么 Rails 3 中的作用域是实现此目的的好方法。或者,您可以实现一个类方法。
我最近在教的课上就遇到过这样的事情,Rails 3版本的代码在这里:https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/app/models/user.rb https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/app/models/user.rb
请参阅 items 方法的定义。规格在这里:https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb
Rails 3.1 更新:正如一位评论者已经指出的那样,Rails 3.1 确实支持 has_many :通过超过一层深度的关联。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)