2012-11-22 58 views
1

我有一个数组Pictures。每张图片has_many评论。从对象数组中获取关联数组?

如果我有一组图片@pictures,我如何从@pictures中的所有图片中获得具有某个属性的所有注释?有一个漂亮的红宝石一个衬为下面的代码?:

@comments = [] 
@pictures.each do |pic| 
    pic.comments.each do |comment| 
    if comment.text == "test" 
     @comments << comment 
    end 
    end 
end 

注:我知道,我也许可以从数据库查询一行得到这个,但我想这将是更有效地使用数据我已经有了,而不是重新查询所有图片的数据库,当我只关心我已经有的图片的某个子集时。

回答

5
@comments = 
@pictures 
.flat_map(&:comments) 
.select{|comment| comment.text == "test"} 
+1

我永远爱Ruby和Rails如何让一切容易... –

1

map + select应该做的伎俩:

@comments = @pictures.map(&:comments).flatten.select{|c| c.text == "test"}