簡體   English   中英

我想在我的示例twitter rails應用程序中找到所有關注者的推文

[英]I want find the tweets of all my followers in my sample twitter rails app

我想找到的鳴叫followed_users

用戶模型

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  

推特模型

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的實際推文。 我想要我的應用推文。

首先,您需要了解如何將rails應用程序與Twitter集成。 為此,您必須使用Twitter API。

  1. 要將rails應用程序與Twitter集成,請閱讀此博客文章 - http://www.manaslutech.com/blogs/3-Ruby-on-Rails-integration-with-Facebook-and-Tw​​itter 您可以跳過Facebook部分,只關注Twitter集成。

  2. 獲得Twitter身份驗證后,您可以獲得關注者Twitter ID或用戶名

  3. 現在,您可以閱讀第2步中所有關注者的推文

Twitter的新v1.1 API允許你這樣做,但你不會從一個電話獲得你的粉絲的推文列表

以下是我接近它的方法:


積分

它不再是oAuth與Twitter連接的情況,您必須通過v1.1身份驗證過程

你需要使用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受到限制


后端

因為你只能得到你的粉絲,然后是推文,你必須把它分為兩個步驟。 我會通過將關注者存儲在他們自己的表中並使用rake任務來每天或每小時獲取他們的最新推文來接近它:

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

tweets
id | username | latest | created_at | updated_at

這將允許您向表中添加Twitter關注者,並使用rake任務更新他們的最新推文:

#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

嘗試這是一件有趣的事情! 我最近制作了一個基於瀏覽器的小游戲,使用twitter進行身份驗證。 通過這樣做,我發現以下資源非常有用:

Sferik ,在github上,提供項目登錄Twitter,作為如何將rails應用程序與twitter的API集成的示例。 那里有很多優秀的代碼,非常簡單。 我用那個項目作為我自己的基礎。

Sferik還提供了嘰嘰喳喳的寶石,並牛逼 ,一個Twitter CLI。 這些將對您的旅程有所幫助。

除了@ royalGhost的答案中建議的資源,我會參考這個SO問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM