Rails 未定义的方法

Rails undefined method

我正在尝试使用雅虎登录并尝试获取令牌但无法执行 so.I 我正在关注此 tutorial


在此行中出现错误“access_token = auth_info[:credentials][:token]
nil:NilClass

的未定义方法“[]”


[omniauth.rb]

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :yahoo_oauth2, 'yahooclientid', 'yahoosecret',
    name: 'yahoo'
end


[家庭控制器]

class HomesController < ApplicationController
  def index
    auth_info = request.env['omniauth.auth']
    access_token = auth_info[:credentials][:token]
    refresh_token = auth_info[:credentials][:refresh_token]
    expires_at = auth_info[:credentials][:expires_at]
  end


当我 运行 gem 列出一些 gem 与已安装的 omniauth 相关的是..

oauth (0.4.7)
oauth2 (1.0.0, 0.8.1)
omniauth (1.3.1)
omniauth-facebook (3.0.0, 1.4.1)
omniauth-oauth (1.1.0)
omniauth-oauth2 (1.4.0, 1.1.1)
omniauth-twitter (1.2.1)
omniauth-yahoo-oauth2 (1.1.0)

您应该使用实例变量或将其全部包装到模型方法中。在这里您可以看到不同的 oauth 集成(linkedin、twitter、gcal)。我不知道你的用例,但我出于不同的原因将数据保存到数据库中。 Linkedin/twitter 显示配置文件属性所需的数据,并且 gcal 令牌对于根据新请求刷新访问非常重要。

社交控制器

def create
  raise :test
  begin
    @profile = current_user.profile
    @social = @profile.socials.find_or_create_from_auth_hash(auth_hash)
    if auth_hash.provider == "google_oauth2"
      flash[:success] = "Your faskyn calendar is now connected to your google calendar!"
    else  
      flash[:success] = "#{@social.provider.camelize} account was successfully updated!"
    end
  rescue
    flash[:warning] = "There was an error while trying to authenticate you!"
  end
  redirect_to edit_user_profile_path(current_user)
end

private

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

social.rb

def self.find_or_create_from_auth_hash(auth_hash)
  calendar not to update the profile
  social_acc = where(provider: auth_hash.provider).first_or_create
  if auth_hash.provider == "google_oauth2"
  social_acc.update(
    uid: auth_hash.uid,
    email: auth_hash.info.email,
    token: auth_hash.credentials.token,
    refresh_token: auth_hash.credentials.refresh_token,
    expires_at: Time.at(auth_hash.credentials.expires_at).to_datetime)
  social_acc
else
  social_acc.update(
    #no first_name, last_name and phone for twitter
    uid: auth_hash.uid,
    token: auth_hash.credentials.token,
    secret: auth_hash.credentials.secret,
    picture_url: auth_hash.info.image,
    location: auth_hash.info.location,
    description: auth_hash.info.description,
    first_name: auth_hash.info.first_name || nil,
    last_name: auth_hash.info.last_name || nil,
    phone: auth_hash.info.phone || nil,
    page_url:   case social_acc.provider
                when 'twitter' then auth_hash.info.urls.Twitter
                when 'linkedin' then auth_hash.info.urls.public_profile
                end
    )
  social_acc
end