嵌套has_many:通过rails 3

Sli*_*k23 4 ruby-on-rails models rails-models ruby-on-rails-3

我知道Rails不支持嵌套的has_many:通过关系,虽然早在Rails 2之前就有关于补丁的谈话和开放票.

我确实遇到了一个非常光滑的插件,但是主分支机构不能与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
Run Code Online (Sandbox Code Playgroud)

所以,通过将其添加到Author模型,能够获得订单将会很棒.

has_many :orders, :through => :products
Run Code Online (Sandbox Code Playgroud)

但是,唉,你不能 - 至少没有插件.所以,我的问题是,当唯一关联是在连接模型,合同之间时,访问所有作者订单的最佳方法是什么?

Wol*_*old 8

如果您没有尝试通过嵌套关联创建对象,并且您只想将它​​用于查找,那么Rails 3中的范围是一种很好的方法.或者,您可以实现一个类方法.

我在最近教过的一堂课中已经把这种事作为一个例子,代码的Rails 3版本在这里:https: //github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/app/车型/ user.rb

请参阅items方法的定义.规范在这里:https: //github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb

Rails 3.1更新:正如一位评论者已经注意到的那样,Rails 3.1确实支持has_many:通过超过一个级别的关联.