0

我对 ruby​​ 和 RoR 很陌生。我想保存当前显示在我的终端上的传入推文。你能解释一下为什么没有保存推文吗?

我在终端中运行“ruby mine_tweets.rb”并出现 status.text 的“puts”,但数据库中没有条目。

mine_tweets.rb

require 'rubygems'
require 'tweetstream'


puts "searching for turkey....should write to database"

TweetStream.configure do |config|
  config.consumer_key       = 'XXXXXXX'
  config.consumer_secret    = 'XXXXXXX'
  config.oauth_token        = 'XXXXXXX'
  config.oauth_token_secret = 'XXXXXXX'
  config.auth_method        = :oauth
end

# search for "turkey" and will print text and screen name and should store other values in db
TweetStream::Client.new.track('turkey') do |status|
  puts status.text + " FROM: @" + status.user.screen_name   
  Tweet.create(:user_id => status.user.id, :tweet_text => status.text, :screen_name     =>status.user.screen_name)
  Tweet.save!

end

@client = TweetStream::Client.new

@client.on_delete do |status_id, user_id|
  Tweet.delete(status_id)
end

模型/推文.rb

class Tweet < ActiveRecord::Base
  attr_accessible :screen_name, :tweet_text, :user_id
end
4

1 回答 1

0

我最近自己也在为此苦苦挣扎。这是我发现的:

为了保存到数据库,您需要:

  • 创建一个数据库。
  • 将应用程序连接到数据库。
  • 创建表和列
  • ..做某事,即。保存、查询等
  • 关闭连接(在退出应用程序之前)

以下是我如何将推文从 Tweet Stream api 保存到 sqlite 本地数据库中。(我强烈建议直接切换到 Postgres,因为 Heroku 不支持 sqlite)。

推文流.rb

require 'sqlite3'
require 'tweetstream'

KEY = 'xxx'
SECRET = 'xxx'
TOKEN = 'xxx'
TOKEN_SECRET = 'xxx'

SEARCH_TERMS = "your search terms"

begin

  db = SQLite3::Database.open "./db/tweets.db"
  db.execute "CREATE TABLE IF NOT EXISTS store_tweets(
    id, INTEGER PRIMARY KEY, 
    tweetid TEXT, 
    text TEXT, 
    screen_name TEXT,
    userid TEXT, 
    user_name TEXT, 
    profile_image_url TEXT,
    language,
    created_at TEXT, 
    received_at TIMESTAMPS)"

    TweetStream.configure do |config|
      config.consumer_key       = KEY
      config.consumer_secret    = SECRET
      config.oauth_token        = TOKEN
      config.oauth_token_secret = TOKEN_SECRET
      config.auth_method        = :oauth
    end

  TweetStream::Client.new.track(SEARCH_TERMS) do |status|
    puts "#{status.text}"
    db.execute( "INSERT INTO store_tweets(
      'tweetid', 
      'text', 
      'screen_name',
      'userid', 
      'user_name', 
      'profile_image_url',
      'language') 
      VALUES (?, ?, ?, ?, ?, ?, ?)",
      [status[:id]], 
      [status.text], 
      [status.user.screen_name],
      [status.user[:id]], 
      [status.user.name], 
      [status.user.profile_image_url],
      [status.lang])
  end

rescue SQLite3::Exception => e
  puts "Exception occured"
  puts e
ensure
  db.close if db
end
于 2014-02-02T16:04:43.293 回答