5

Simple OmniAuth チュートリアル ( http://asciicasts.com/episodes/241-simple-omniauth ) に従ったところ、Twitter アカウントでサービスにログインできました。次に、twitter API にアクセスし、アプリからツイートします。私のコードは次のとおりです。

class TwitterController < ApplicationController

def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("KEY", "SECRET",
    {
        :site => "http://api.twitter.com"
    })
    # now create the access token object from passed values
    token_hash =
    {
      :oauth_token => oauth_token,
      :oauth_token_secret => oauth_token_secret
    }
    access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
    return access_token
end

def tweet
    # Exchange our oauth_token and oauth_token secret for the AccessToken instance.
    @access_token = prepare_access_token(current_user.token, current_user.secret)

    @response = @access_token.request(:post, "http://api.twitter.com/1/statuses/update.json", :status => "Tweet pela API")

    render :html => @response.body
end

end

レンダリング ラインは何もしません。さらに、付け加えると

<p><%= @response %></p>

私の見解では、私は得る

#<Net::HTTPUnauthorized:0x2ac5149e94f0>

それでも、Twitter アカウントからユーザー名を取得できます。

私のユーザーモデルは次のとおりです。

class User < ActiveRecord::Base
def self.create_with_omniauth(auth)  
       create! do |user|  
         user.provider = auth["provider"]  
         user.uid = auth["uid"]  
         user.name = auth["user_info"]["name"] 
         user.token = auth['credentials']['token'],
         user.secret = auth['credentials']['secret'] 
       end  
    end  
 end

私は何を間違っていますか?

4

2 に答える 2

3

私は問題を理解しました、そして今私はかなりばかげていると感じます。ユーザーモデルにカンマがありましたが、そこにあるべきではありません。モデルは

class User < ActiveRecord::Base
    def self.create_with_omniauth(auth)  
       create! do |user|  
         user.provider = auth["provider"]  
         user.uid = auth["uid"]  
         user.name = auth["user_info"]["name"] 
         user.token = auth['credentials']['token']
         user.secret = auth['credentials']['secret'] 
       end  
    end  
end

そして今、すべてが正常に動作します。

于 2011-01-06T13:16:03.593 に答える
2

これを手動でコーディングするのではなく、twitter gem(gem install twitter)を使用してみてください。構文は次のとおりです。

httpauth = Twitter::HTTPAuth.new(twitterName, twitterPass)
client = Twitter::Base.new(httpauth)
client.update(yourTweetText)
于 2011-01-05T02:57:50.987 に答える