vjhbr
vjhbr

Reputation: 1

-undefined method `user' for nil:NilClass

On the update controller action, rails returns following error,

undefined method `user' for nil:NilClass

Issue is supposed to be in following,

def update
  @profile = Profile.find_by(user_id: params[:id])
  if @profile.user == current_user
    @profile.update(profile_params) 
    flash[:info] = "Profile successfully updated" 
  else

It doesn't make sense why this is an issue, since I used the exact same code to find profiles in my other actions and they worked perfectly.

Upvotes: 0

Views: 141

Answers (1)

Cjmarkham
Cjmarkham

Reputation: 9700

Profile.find_by is returning nil ie: no user was found. So, when you try @profile.user, you are trying to access user on a nil.

Make sure the profile exists with the user_id matching params[:id] and that params[:id] isn't blank or nil.

A way to get rid of the fatal error would be to check if @profile is nil or not before using it:

def update
  @profile = Profile.find_by(user_id: params[:id])
  if @profile.present? 
    if @profile.user == current_user
      @profile.update(profile_params) 
      flash[:info] = "Profile successfully updated" 
    else
    end
  else
    # Profile not found
  end
end

Or, you could use the bang variation of find_by:

Profile.find_by!

Which will throw an exception if nothing is found (which you can then rescue from)

Upvotes: 2

Related Questions