1

の配列があり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

注: おそらくデータベース クエリから 1 行でこれを取得できることはわかっていますが、すべての画像についてデータベースに再度クエリを実行するよりも、既存のデータを使用する方が効率的であると考えています。私がすでに持っている写真の特定のサブセット。

4

2 に答える 2

5
@comments =
@pictures
.flat_map(&:comments)
.select{|comment| comment.text == "test"}
于 2012-11-22T15:27:00.707 に答える
1

map+selectトリックを行う必要があります:

@comments = @pictures.map(&:comments).flatten.select{|c| c.text == "test"}
于 2012-11-22T15:21:40.630 に答える