Reputation: 304
My application checks for the user existing, and if they don't, it calls this line:
p = Player.create!(uid: id, nick: session[:current_user][:nick], profile_complete: false)
which for some reason is throwing an error:
undefined method `[]' for nil:NilClass
Anybody have any idea why?
Upvotes: 0
Views: 54
Reputation: 1022
in Rails you can also use method try
p = Player.create! uid: id, nick: session[:current_user].try(:[], :nick), profile_complete: false
Upvotes: 0
Reputation: 4860
This is the cause: session[:current_user][:nick]
, what means that you do not have either session or current_user in the session in this moment.
You should check that the current_user exists before calling .create!
if session[:current_user] && (nick = session[:current_user][:nick])
p = Player.create!(uid: id, nick: nick, profile_complete: false)
end
Upvotes: 1
Reputation: 26193
You can conditionally address this exception by sequentially checking whether session[:current_user]
, then session[:current_user][:nick]
exists:
if session[:current_user]
if session[:current_user][:nick]
p = Player.create!(uid: id, nick: session[:current_user][:nick], profile_complete: false)
end
end
Upvotes: 1