ruby-on-railsfacebookomniauth-facebook

login using omniauth-facebook "undefined method `slice' for nil:NilClass" error


i have a problem using omniauth-facebook. i tried to login in my rails app using facebook but its giving me an error and the env['omniauth.auth'] is throwing a nil value here is the error..

 NoMethodError at /auth/facebook/callback
 undefined method `slice' for nil:NilClass

here is my model

#fields
  field :provider
  field :uid
  field :name
  field :oauth_token 
  field :oauth_expires_at , type: DateTime

  #functions
  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).find_or_initialize_by.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

and this is my controller

  def create
    user = Usersfb.from_omniauth(ENV["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end
  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end

my routes.rb

  root 'main#index'
  get 'session/destroy' , to: 'session#destroy'
  get 'auth/:provider/callback' => 'session#create'

Solution

  • You have mistake in controller action:

    def create
      #user = Usersfb.from_omniauth(ENV["omniauth.auth"])
      user = Usersfb.from_omniauth(request.env["omniauth.auth"])
      session[:user_id] = user.id
      redirect_to root_url
    end
    

    ENV it is environment variables not request.env, this ENV["omniauth.auth"] return nil and this where(auth.slice(:provider, :uid)) trying slice nil that raise undefined method 'slice' for nil:NilClass .