简体   繁体   English

从活动记录关系中提取对象的最佳方法

[英]best way to extract object from an activerecord relation

What would be the best way to iterate through an active relation. 迭代活跃关系的最佳方法是什么。 Let's say I have an active relation object returned. 假设我有一个活动的关系对象返回。 I want to break it down into the corresponding category of their parent. 我想将其细分为他们父母的相应类别。 I have 12 categories for products, and I'm building 12 dropdowns! 我有12个产品类别,并且正在构建12个下拉菜单!

Product belongs to category Product has many favorites User has_many :products, through: :favorites 产品属于类别产品有很多收藏夹用户has_many:products,通过::favorites

Favorite.includes(:product).where('user_id = ?', current_user.id).each do |favorite|
...?...
end 

you could try something like: 您可以尝试以下方法:

grouped_favorites = Favorite.includes(:product => :category)
                            .where('user_id = ?', current_user.id)
                            .group_by {|favorite| favorite.product.category }

grouped_favorites.each do |category, favorites|
   favorites.each do |favorite|
     ...?...
   end
end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM