gpt4 book ai didi

ruby-on-rails - 嵌套 has_many :through in rails 3

转载 作者:行者123 更新时间:2023-12-04 06:30:43 25 4
gpt4 key购买 nike

我知道 Rails 不支持嵌套的 has_many :through 关系,尽管早在 Rails 2 就已经有关于补丁的讨论和公开票。

我确实来了across a plugin这很漂亮,但是主分支不能与 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

但是,唉,你不能——至少没有插件。所以,我的问题是当唯一的关联是连接模型契约(Contract)之间时,访问所有作者订单的最佳方法是什么?

最佳答案

如果您不想通过嵌套关联创建对象,而只想将其用于查找,那么 Rails 3 中的作用域是实现此目的的好方法。或者,您可以实现一个类方法。

我最近在教的一门课上有这样的例子,代码的Rails 3版本在这里:
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

Rails 3.1 更新:正如一位评论者已经指出的那样,Rails 3.1 确实支持 has_many :通过多于一层深度的关联。

关于ruby-on-rails - 嵌套 has_many :through in rails 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4720492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com