Search code examples
ruby-on-railsdeviseomniauthomniauth-facebook

NoMethodError with Devise and Omniauth -rails


I am in the process of trying to integrate Omniauth Facebook login with Devise for a Rails application that I'm currently in the early stages of developing. I'm a (very) junior developer, and I've hit a roadblock which I'm unsure how to resolve.

So far, I have managed to install the Devise gem successfully, and have managed to get the Omniauth Facebook working up to the point of logging into the app with Facebook (by following the documentation at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview) - however, on the redirect back to my app, the following error message displays:

NoMethodError in Users::OmniauthCallbacksController#facebook undefined method `name=' for # user.name = auth.info.name # assuming the user model has a name

The code snippets that I think would be helpful to resolve the issue are as follows:

My user model:

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

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end

    def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.email = auth.info.email
        user.password = Devise.friendly_token[0,20]
        user.name = auth.info.name   # assuming the user model has a name
        user.image = auth.info.image # assuming the user model has an image
      end
    end


end

My routes file:

Rails.application.routes.draw do

  devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
  root to: "restaurants#index"

  devise_scope :user do
    get 'sign_out', :to => 'devise/sessions#destroy', only: :destroy_user_session
  end

  resources :restaurants do
    resources :reviews
  end

end

I hope that this is enough to help me diagnose the problem, though please do let me know if any further code is required. Huge thanks in advance!


Solution

  • Does your user model have a name and image? Try removing these two lines:

    user.name = auth.info.name   # assuming the user model has a name
    user.image = auth.info.image # assuming the user model has an image