2014-01-13 18 views
0

我想找到的followed_users我想找到我在我的樣本Twitter上所有的追隨者的鳴叫Rails應用程序

用戶模式

class User < ActiveRecord::Base 
    has_many :tweets, dependent: :destroy 
    has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
    has_many :followed_users, through: :relationships, source: :followed 
    has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy 
    has_many :followers, through: :reverse_relationships, source: :follower 

分享Tweet模式的鳴叫

class Tweet < ActiveRecord::Base 
    belongs_to :user 

關係模型

class Relationship < ActiveRecord::Base 
    belongs_to :follower, class_name: "User" 
    belongs_to :followed, class_name: "User 

請幫我看看

  • 的鳴叫我所有的followed_users
  • 鳴叫應:created_at責令

編輯:
我不想實際Twitter的推文。我想要我的應用程序的推文。

回答

1

首先,你需要了解如何將您的Rails應用程序與Twitter集成。爲了做到這一點,你必須使用Twitter API。

  1. 對於Rails應用與Twitter整合,閱讀此博客 後 - http://www.manaslutech.com/blogs/3-Ruby-on-Rails-integration-with-Facebook-and-Twitter 。您可以跳過Facebook的一部分,只是專注於Twitter的整合 。

  2. 一旦你擁有了Twitter的認證,就可以得到追隨者的Twitter ID或用戶名現在

  3. ,你可以從步驟#閱讀追隨者所有的鳴叫2

+0

我想知道如何做到這一點,而不是使用API – rejin

0

這是一個有趣要嘗試做的事情!我最近做了一個小的基於瀏覽器的遊戲,利用Twitter進行身份驗證。這樣做,我發現以下資源非常有用:

Sferik,在github上提供項目Sign in With Twitter作爲如何將您的Rails應用程序與Twitter的API集成的示例。很多偉大的代碼在那裏,非常簡單。我用這個項目作爲我自己的基礎。

Sferik還提供twitter gem和t,一個twitter CLI。這些將對您的旅程有所幫助。

除了資源建議在@royalGhost's answer,我要提到this SO question

1

Twitter's new v1.1 API讓你有點做到這一點,但你不會從一個電話讓你的追隨者的tweet的列表

以下是我想接近它:


集成

它不再是OAuth的的情況下,以與Twitter連接,你必須要經過v1.1 authentication process

你需要使用Twitter Gem,使您的Rails應用程序:

#config/initializers/twitter.rb 
#creates a constant 
TWITTER = Twitter::REST::Client.new do |config| 
    config.consumer_key  = "YOUR_CONSUMER_KEY" 
    config.consumer_secret  = "YOUR_CONSUMER_SECRET" 
    config.access_token  = "YOUR_ACCESS_TOKEN" 
    config.access_token_secret = "YOUR_ACCESS_SECRET" 
end 

然後就可以調用Twitter的API直接:

#app/views/shared/footer.html.erb 
<%= TWITTER.followers(213747670) %> 

你必須記住,Twitter的新API是throttled


後臺

因爲你只能得到你的追隨者,然後推文,你必須做到這兩個步驟。我會通過存儲在自己的表中的追隨者,並使用rake task得到他們最新的鳴叫接近它,每天或每小時:

#app/models/tweet.rb 
Class Tweet < ActiveRecord::Base 
end 

tweets 
id | username | latest | created_at | updated_at 

這將讓你的Twitter追隨者添加到表中,並用耙子任務來更新他們的最新的tweet:

#app/controllers/tweets_controller.rb 
def new 
    @tweet = Tweet.new 
end 

def create 
    @tweet = Tweet.new(tweet_params) 
    @tweet.save 
end 

private 

def tweet_params 
    params.require(:tweet).permit(:username) 
end 

#lib/tasks/tweet.rake 
namespace :tweets do 
    desc "Update Latest Tweets" 
    task :latest => :environment do 
     followers = Tweet.all.map(&:username).to_a 
     followers.each do |follower| 
      tweets = TWITTER.user_timeline(follower) 
      follower.update_attributes({latest: tweets.first}) 
     end 
    end 
end 

你可以從控制檯運行這樣的rake任務:rake tweets:latest

相關問題