Rails - 更好的流量控制 - 循环

时间:2012-07-09 22:50:11

标签: ruby-on-rails ruby ruby-on-rails-3

我正在抓取价值数据:name,uid,highschool_name,graduateschool_name是这样的:

def add_friends
    facebook.get_connections("me", "friends", :fields => "name, id, education").each do |hash|
      self.friends.where(:name => hash['name'], 
                         :uid => hash['id'], 
                         :highschool_name => hash['education']['school']['name'] unless hash["education"].blank?,
                         :graduateschool_name => hash['education']['school']['name'] unless hash["education"].blank?).
                   first_or_create
    end
end

从哈希数组:

"education": [
    {
      "school": {
        "id": "110703012290674", 
        "name": "Kunskapsgymnasiet Malmö"
      }, 
      "year": {
        "id": "136328419721520", 
        "name": "2009"
      }, 
      "type": "High School"
    }, 
    {
      "school": {
        "id": "112812485399398", 
        "name": "Malmö University"
      }, 
      "year": {
        "id": "118118634930920", 
        "name": "2012"
      }, 
      "concentration": [
        {
          "id": "104076956295773", 
          "name": "Computer Science"
        }
      ], 
      "type": "Graduate School", 
      "classes": [
        {
          "id": "165093923542525", 
          "name": "Programmering", 
          "description": "Kursen fokuserar på metoder och tekniker vid utveckling av webbapplikationer med hjälp av HTML5."
        }
      ]
    }
  ], 

编辑: 这段代码很有用。我想从这一系列哈希中选择每个hichschool和研究生院并保存它。

1 个答案:

答案 0 :(得分:0)

high_schools = response['education'].collect{|ed| ed['school']['name'] if ed['type'] == "High School" } 
grad_schools = response['education'].collect{|ed| ed['school']['name'] if ed['type'] == "Graduate School" }