Rails从具有关联的哈希过滤值

时间:2014-01-06 01:20:39

标签: ruby-on-rails ruby hash

我有以下哈希,我需要过滤掉电影(电影名称是哈希键),如果它们属于某种类型。问题在于关联。

{"Kaze no tani no Naushika"=>
  {:count=>127, 
   :genres=>#<ActiveRecord::Associations::CollectionProxy 
   [#<Genre genre_id: 911, name: "Action", ParentID: nil>, 
    #<Genre genre_id: 912, name: "Adventure", ParentID: nil>, 
    #<Genre genre_id: 913, name: "Animation", ParentID: nil>, 
    #<Genre genre_id: 923, name: "Fantasy", ParentID: nil>, 
    #<Genre genre_id: 936, name: "Science Fiction", ParentID: nil>]>},** 
 "Mononoke-hime"=>
  {:count=>53, 
   :genres=>#<ActiveRecord::Associations::CollectionProxy 
   [#<Genre genre_id: 912, name: "Adventure", ParentID: nil>, 
    #<Genre genre_id: 913, name: "Animation", ParentID: nil>, 
    #<Genre genre_id: 923, name: "Fantasy", ParentID: nil>]>}, 
 "Sen to Chihiro no kamikakushi"=>
  {:count=>102, 
   :genres=>#<ActiveRecord::Associations::CollectionProxy 
   [#<Genre genre_id: 912, name: "Adventure", ParentID: nil>, 
    #<Genre genre_id: 913, name: "Animation", ParentID: nil>, 
    #<Genre genre_id: 921, name: "Family", ParentID: nil>]>},...

我使用rails 4.0.0。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用Hash#selectEnumerable#find的组合:

adventure_movies = movies.select do |movie_name, movie_attrs|
  movie_attrs[:genres].find { |genre| genre.name == 'Adventure' }
end