Nick
Nick

Reputation: 304

Create! method throwing nomethoderror

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

Answers (3)

Andrew Kozin
Andrew Kozin

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

Rafa Paez
Rafa Paez

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

zeantsoi
zeantsoi

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

Related Questions