我在订阅
和文章
之间有一个has_many
关系,一篇文章有一个产品
。
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
现在。我想简单地从我的订阅中获取所有产品。
解决方案包括
:
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”,因此返回的产品
将表现得像一个关系。要在 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
集合。
关于ruby-on-rails-4 - 如何使用事件记录方法获取关联通过集合(代理集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26255588/