我有一个Pictures
数组。每张图片has_many
评论。
如果我有一系列图片@pictures
,如何从@pictures
中的所有图片中获取具有特定属性的所有评论?以下代码是否有一个很好的Ruby单行程序?:
@comments = []
@pictures.each do |pic|
pic.comments.each do |comment|
if comment.text == "test"
@comments << comment
end
end
end
注意:我知道我可以从数据库查询中获得一行,但我认为使用我已有的数据会更有效,而不是重新查询数据库中的所有图片,当我只关心我已经拥有的某一部分图片。
答案 0 :(得分:5)
@comments =
@pictures
.flat_map(&:comments)
.select{|comment| comment.text == "test"}
答案 1 :(得分:1)
map
+ select
应该可以解决问题:
@comments = @pictures.map(&:comments).flatten.select{|c| c.text == "test"}