如何使用活动记录方法获取关联的直通集合(代理集合)



我在SubscriptionArticle之间有has_many关系,一篇文章有Product

class Subscription < ActiveRecord::Base
  has_many :articles
end
class Article < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :product
end
class Product < ActiveRecord::Base
  has_many :subscriptions
end

现在。我想简单地从我的订阅中获取所有产品。

解决方案includes:

class Subscription < ActiveRecord::Base
  has_many :articles
  def products
    articles.includes(:product).map{|a| ap.product} # Or .map(&:product)
  end
end

解决方案has_many :through:

class Subscription < ActiveRecord::Base
  has_many :articles
  has_many :products, through: articles
end

第一种方法的缺点是,它不返回可以链接的集合(例如subscription.products.pluck(:id)),而是返回一个简单的数组。

第二个在语义上并不完全正确:我不希望它成为一个全面的关联,而只是一个获取列表的助手。

我只是忽略了一些允许我获取关联直通项的activerecord方法吗?

我通常会将其写为"has_many through",因此返回的products将表现为一个关系。要在Subscription方法中实现类似的功能,可以将缺少的has_many关联添加到Product,并在Product联接上合并订阅文章:

class Product < ActiveRecord::Base
  has_many :articles
end
class Subscription < ActiveRecord::Base
  has_many :articles
  def products
    Product.joins(:articles).merge(articles)
  end
end

在这种情况下,Subscription#products将返回一个ActiveRecord集合。

最新更新