嵌套的has_many:通过rails 3 [英] nested has_many :through in rails 3

查看:113
本文介绍了嵌套的has_many:通过rails 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Rails不支持嵌套的has_many:through关系,尽管早在Rails 2以来就一直在讨论和发布补丁补丁.

I know Rails doesn't support nested has_many :through relationships, though there's been talk and an open ticket about a patch since as early as Rails 2.

我确实在一个非常漂亮的插件上出现了一个插件,但是master分支不适用于Rails 3,我很犹豫是否将其用于应用程序中的关键任务,因此缺乏积极的最新开发成果.所以-处理这些关系的最佳方法是什么.

I did come across a plugin that's pretty slick, but the master branches don't work with Rails 3 and I'm hesitant to use it for mission critical tasks in the app hence the lack of active recent development. So -- what's the best way to deal with these relations.

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模型中,能够获得此订单将是一件很棒的事情:

So, all the being what it is it would be great to be able to get at orders this by adding this to the Author model:

has_many :orders, :through => :products

但是a,您不能-至少没有插件.因此,我的问题是,当联接模型(合同)之间唯一的关联时,访问所有作者订单的最佳方法是什么?

But alas, you cannot -- at least without the plugin. So, my question is what's the best approach to accessing all of an author's orders when the only association is between the join model, Contracts?

推荐答案

如果您不尝试通过嵌套关联创建对象,并且只想将其用于查找,那么Rails 3中的作用域是一种不错的方法去做这个.或者,您可以实现一个类方法.

If you're not trying to create objects through the nested association, and you want to use it for lookup only, then scopes in Rails 3 are a great way to do this. Alternatively you could implement a class method.

在我最近教过的一堂课中,我以这种事情为例,Rails 3版本的代码在这里: https://github.com/wolframarnold/Efficient -TDD-Rails3/blob/master/app/models/user.rb

I've had this kind of thing as an example in a class I taught recently, the Rails 3 version of the code is here: 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

See the definition of the items method. The specs are here: https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb

Rails 3.1更新:正如一位评论者已经指出的那样,Rails 3.1确实支持has_many:通过多个层次以上的关联.

Rails 3.1 update: As one commenter already noted, Rails 3.1 does support has_many :through associations more than one level deep.

这篇关于嵌套的has_many:通过rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆