将数据从api调用保存到我的模型中

时间:2014-04-29 13:52:16

标签: ruby-on-rails ruby facebook-graph-api activerecord

我希望将api调用的结果保存到我的模型中,并且想知道如何处理这个...

我有一个名为Post的模型,我的api调用现在返回我需要的内容。我只是不确定如何将api调用返回的值传入模型,到目前为止我已经有了这个

def get_feed
  uri = URI(FACEBOOK_URL)
  response = HTTParty.get(uri)
  results = JSON.parse(response.body)
  puts formatted_data(results)
end

def formatted_data(results)
# Return only if there are results
  return unless results
      results['data'].map { |m| 
        {
          message: m['message'],
          picture: m['picture'],
          link: m['link'],
          object_id: m['object_id']
         } }.compact #removes nil objects from array

 Post.where(message: message, picture: picture, link: link, object_id: object_id).first_or_create!
end

因此,如果我有10个消息实例,我如何将它们全部保存到模型中

由于

3 个答案:

答案 0 :(得分:1)

使用此:

 def formatted_data(results)
    # Return only if there are results
    return unless results
    results['data'].map { |m|
      attrs = { message: m['message'], picture: m['picture'], link: m['link'], object_id: m['object_id']}
      Post.where(attrs).first_or_create! do |post|
        post.attributes = attrs
      end
    }

  end

假设你的哈希看起来像:

{
"data" => 
{"key1" => {"message" => "value1", "picture" => "value2", "link" => "value3", "object_id" => "value4" } ,
"key2" => {"message" => "value1", "picture" => "value2", "link" => "value3", "object_id" => "value4" } ,
... 
...
}}

答案 1 :(得分:0)

如果您打印results,将会清楚如何执行此操作。比,你可以从这里开始:

 messages = results['data'].map{ |m| m['message'] }

这将为您提供messages数组

中的所有消息

答案 2 :(得分:0)

def formatted_data(results)
# Return only if there are results
  return unless results
  results['data'].each do |m| 
    Post.where(message: m['message'], picture: m['picture'], link: m['link'], object_id: m['object_id']).first_or_create!
  end 
end

不确定你的意思 - 从数组中删除nil对象。我假设你的意思是facebook会返回一些你不会在这种情况下使用的数据,然后检查以确保在创建帖子实例之前你想要的所有数据