0
votes

I followed Ryan Bates'/RailsCasts tutorial for cookies login and remind me functionality in an application I am building.

[reference: http://railscasts.com/episodes/274-remember-me-reset-password?view=comments] I wanted to introduce his OmniAuth functionality for the same application.

[reference: http://railscasts.com/episodes/235-omniauth-part-1] I'm not using devise. I am correctly loading the Twitter app page, the error occurs when redirecting back to my application. I have the callback URL correctly set within Twitter.

I am getting an undefined method "authentications" for nil:NilClass error with OmniAuth and my authentications_controller. Specifically my console reads:

NoMethodError (undefined method authentications for nil:NilClass):app/controllers/authentications_controller.rb:9:in create'.

Here is the Authentications Controller code:

class AuthenticationsController < ApplicationController

  def index
    authentications = Authentication.all
  end

  def create
    auth = request.env["omniauth.auth"]
    current_user.authentications.create(:provider => auth['provider'], :uid => auth['uid'])
    flash[:notice] = "Authentication was successful."
    redirect_to authentications_url
  end

Here is the current_user helper method in my Applications Controller.

private
  def current_user
    @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
  end
  helper_method :current_user

User has many authentications. Authentications belong to user.

I'd like to enable OmniAuth to work with Twitter so users can login with their Twitter account by avoiding the error I am receiving while maintaining my current_user code

Help is appreciated.

1

1 Answers

0
votes

You're not taking into account the case where the user is not logged in. What you're doing in your create action is associating the user's account on your site to his account on Twitter.

You can't use current_user without making sure that the user is logged in. Otherwise it will return nil, and that's why it's saying undefined method authentications for nil:NilClass.

Take a look at the next railscast that goes into more details: http://railscasts.com/episodes/236-omniauth-part-2