如何获得模型字段的汇总列表?

问题描述 投票:0回答:1

我正在使用RoR5。我有这个模型

class Article < ApplicationRecord
    ...
  has_and_belongs_to_many :contributors, :optional => false

然后假设我有一系列文章模型。我如何获得贡献者的完整列表?我尝试过了...

articles.each do |article|
  @contributors << article.contributors
end
@contributors

但是,当我尝试在视图中访问贡献者的属性(例如“ id”时,出现这些错误

undefined method `id' for #<Contributor::ActiveRecord_Associations_CollectionProxy:0x00007f828a834028>

什么是汇总贡献者列表的正确方法?

ruby-on-rails arrays model relation
1个回答
0
投票
@contributors = Contributor.joins(:articles).where(articles: {id: articles})

您可以在Specifying Conditions on the Joined Tables中检出docs了解更多信息。

[这自然假定

class Contributor < ApplicationRecord has_and_belongs_to_many :articles end

您收到此错误:

undefined method `id' for #<Contributor::ActiveRecord_Associations_CollectionProxy:0x00007f828a834028>

...因为您要在此处创建arrayActiveRecord_Associations_CollectionProxy

articles.each do |article|
  @contributors << article.contributors
end
@contributors

...因为:

article.contributors

...返回ActiveRecord_Associations_CollectionProxy。而且,很自然地,正如错误所示,ActiveRecord_Associations_CollectionProxy没有方法id

© www.soinside.com 2019 - 2024. All rights reserved.