gpt4 book ai didi

ruby-on-rails - 事件记录 :has_many and includes

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:47 25 4
gpt4 key购买 nike

我正在使用 rails 4.2.0 - 这是我的模型:

class Customer < ApplicationRecord
has_many :meters, -> { includes :contracts }
end

class Meter < ApplicationRecord
belongs_to :customer
has_many :contracts
end

class Contract < ApplicationRecord
belongs_to :meter
end

现在,我想显示一个客户的所有契约(Contract)。根据Rails Guides我应该能够做到这一点:

@customer.meters.contracts

但是,它不起作用。这是错误消息:

undefined method `contracts' for #<Meter::ActiveRecord_Associations_CollectionProxy:0x007fb0385730b0>

在这种情况下最好的方法是什么?感谢您的帮助!

最佳答案

在您的示例中,每个模型类仅代表数据库记录的这些实例之一,即您的 Meter 类仅代表 中的一个 meter 行米表。所以考虑到这一点,你可以看到 meter has_many contracts 的声明意味着那些 meter 中的每一个code> 实例有很多 contracts

让我们把这一行分解:@customer.meters.contracts

您有您的@customer 实例,您要求它提供所有的计量表:@customer.meters。该meters 方法的返回值是属于该@customermeters 的集合。由于它是具有多个合约的 meter 实例,因此您不能以这种方式向 meter 集合请求它们的合约。

您可以向单个仪表询问它:@customer.meters.first.contracts 或者您可以遍历所有仪表并获取所有契约(Contract):

@customer.meters.flat_map(&:contracts) # => an array of all the contracts

或者,更一般地说,您可能希望在 View 中显示客户契约(Contract)的列表:

<% @customer.meters.each do |meter| %>
<% meter.contracts.each do |contract|
// display the contract
<% end %>
<% end %>

但是,您可以通过meters 关联将所有contracts 关联到customer:

class Customer < ApplicationRecord
has_many :meters, -> { includes :contracts }
# ActiveRecord's shorthand declaration for associating
# records through a join table, in this case 'meters'
has_many :contracts, through: :meters
end

通过添加 has_many X, through: Y,您是说客户记录通过连接表 与另一个表 X 中的记录相关联>Y.

有了这个,给定一个 客户 和现有的 meters 以及那些有现有 contracts 的meters,你将能够调用 @customer.contracts 和 ActiveRecord 将通过加入客户的 meters 和他们的 contracts 来获取 contracts 并返回 contracts 集合。

有关 Rails Has Many Through 协会的更多信息:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

关于ruby-on-rails - 事件记录 :has_many and includes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44270822/

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