授权后的Omniauth回调处理

时间:2013-05-15 02:45:11

标签: ruby-on-rails ruby devise omniauth twitter-oauth

在我的Rails应用程序中,我有userauthorization个表来处理用户和身份验证数据。我设置了Devise和Omniauth使用Twitter注册,它重定向到Twitter,但在返回我的应用程序后,它会出现如下错误:

NoMethodError at /users/auth/twitter/callback 
undefined method `authorizations' for #<Class:0xbdc8100>

在哪一方面,我出错了,我该如何解决这个问题呢?

以下是相关部分:omniauth_callbacks_controller.rb

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
    def all
        user = User.authorizations.from_auth(auth_hash)
        if user.persisted?
            flash.notice = "Signed in!"
            sign_in_and_redirect user
        else
            session["devise.user_attributes"] = user.attributes
            redirect_to new_user_registration_url
        end
    end


    alias_method :twitter, :all

    protected
    def auth_hash
        request.env['omniauth.auth']
    end
end

authorization.rb

class Authorization < ActiveRecord::Base

    attr_accessible :uid, :provider
    belongs_to :user

    def self.from_auth(auth)
        where(auth.slice(:provider, :uid)).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
    end
end

user.rb

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:twitter, :facebook]

# Setup accessible (or protected) attributes for your model
    attr_accessible :email, :password, :password_confirmation, :remember_me, :name
# attr_accessible :title, :body

    has_many :authorizations, dependent: :destroy

end

1 个答案:

答案 0 :(得分:1)

您的问题就在这一行......

user = User.authorizations.from_auth(auth_hash)

您在类User上调用授权,但作为属性,需要在User类的实例(即特定用户)上调用它。