2012-01-04 4 views
0

私はさまざまなニュースサイトからコメントを得て、何らかの処理をしようとしています。たとえば、https://graph.facebook.com/comments/?ids=http://techcrunch.com/2012/01/04/mechanical-engineering-community-grabcad-grabs-4-million/RailsとKoalaを使用してサイトからコメントを取得する

私はコメントがありますが、レールやコアラを使ってmysqlデータベース(または他のデータベース)に格納する方法はわかりません。

すべてのヘルプ/ヒントがずっと

答えて

-1

を高く評価しているあなたは、Rubyの

data = ActiveSupport::JSON.decode(json_data) 

を使用してJSONを解析して、単にデータを反復し、ActiveRecordの

data["data"].each do |comment| 
    Comment.create!(:message => comment.message, ...) 
end 
+0

どうすればjson_dataを作成できますか? – user1130493

+0

特に私はFacebookからそれを取得しようとしています。私のようなすべてのテキストをコピーして私のファイルに貼り付けたいのではありません。私は持っているリンクを渡すことによってこれを行う任意の効率的な方法はありますか? – user1130493

0
を使用してデータベースに格納することができます

下記のコードを確認してください:

url_commented_on = "http://techcrunch.com/2012/01/04/mechanical-engineering-community-grabcad-grabs-4-million/" 
fb_comments_url = "https://graph.facebook.com/comments/?ids="+url_commented_on 
fb_comments_json = open(fb_comments_url).read 
fb_comments_data = ActiveSupport::JSON.decode(fb_comments_json) 

# If you want to play around, this gets you the first comment 
fb_comments_data[url_commented_on]["comments"]["data"].first 
# and this gets you the first comment's message 
fb_comments_data[url_commented_on]["comments"]["data"].first["message"] 

# You could save them in your db like this: 
fb_comments = fb_comments_data[url_commented_on]["comments"]["data"] 
fb_comments.each do |fb_comment| 
    # Your comment Model here 
    fb_commenter_name = fb_comment["from"]["name"] 
    fb_comment_message = fb_comment["message"] 
    fb_comment_creation_date = fb_comment["created_time"] 
    # Your comment Model 
    comment = CommentModel.new 
    comment.author = fb_commenter_name 
    comment.comment_text = fb_comment_message 
    # Don't overwrite your own "created_at" attribute 
    # Instead, use an additional column in the db for storing the date fb gives you 
    comment.fb_created_at = fb_comment_creation_date 
    comment.save! 
end