Hamel Desai Hamel Desai - 2 months ago 12
Ruby Question

"undefined method `user' for nil:NilClass"

Hello everyone I am new to rails and for some reason I keep getting an error

"undefined method `user' for nil:NilClass".

I have pasted an image of the error on the bottom and I posted the code below.

-Thank you.

Image Error

Controller (registeredapps_controller) create#action:

class RegisteredappsController < ApplicationController

def create
@registeredapp = Registeredapp.new(registeredapp_params)
@registeredapp.user = current_user

unless RegisteredappPolicy.new(current_user, @registeredapp).create?
flash[:alert] = "not authorized"
redirect_to user_registeredapps_path(current_user.id)
end

if @registeredapp.save
flash[:notice] = "You successfully registered your app."
redirect_to user_registeredapp_path(current_user.id, @registeredapp.id)
else
flash.now[:alert] = "There was an error registering your app. Please try again."
render :new
end
end


Policies (using Pundit Gem) registeredapp_policy.rb

class RegisteredappPolicy

def initialize(user, registeredapp)
@registeredapp = registeredapp
@user = user
end

def create?
if @user.present?
@user = @registerdapp.user
else
false
end
end


Here are my models

User.rb

class User < ApplicationRecord

# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable

def avatar_url(size)
gravatar_id = Digest::MD5::hexdigest(self.email).downcase
"http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}"
end

has_many :registeredapps
end


Registeredapp.rb

class Registeredapp < ApplicationRecord
belongs_to :user
has_many :events
end

Answer

Your issue is that the instance variable @registeredapp is mispelled in the RegisteredappPolicy class under the create? method.

It currently is

def create?
  if @user.present?
    @user = @registerdapp.user
  else
    false
  end
end

whereas the variable defined in the initialize is @registeredapp you're missing an e