Reputation: 5097
I'm using Devise and Omniauth. So, I'm supposed to have a current_user
method available in my controllers. Indeed, for example, in my tasks_controller
:
def index
@tasks_remaining = Task.where(:user => current_user, :done => false)
@tasks_done = Task.where(:user => current_user, :done => true)
end
current_user
does work as expected. Very oddly, RubyMine warns me that current_user
is not found and underlines it gray. But this piece of code works anyway.
However, in my authentications_controller
,
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
sign_in_and_redirect(:user, authentication.user)
else
current_user.authentications.create(:provider => ominauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "success"
redirect_to authentication_url
end
end
Here, I get an error when that line with current_user
executes. It says:
undefined method `authentications' for nil:NilClass
I have debugged to this point and found that current_user
variable is indeed not present in this scope.
So, why is it working in one controller and missing in another? I'm using Rails 4 and Ruby 2. I'm following Railscast 235 and 236.
Upvotes: 0
Views: 1397
Reputation: 7225
the error does not mean that current_user method, is not found it returns nil because nobody is signed in.
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
have you written condition like 'elsif current_user' in your authentications controller code?
as i see you have copied this code from railscasts omniauth #1, i suggest watching railscasts omniauth #2 also.
Upvotes: 2