简体   繁体   中英

Undefined method for nil:NilClass on `current_user`

I have two models in my Rails application:

class User < ActiveRecord::Base
  has_many :restaurants
end

class Restaurant < ActiveRecord::Base
  belongs_to :user
end

When I try to get user restaurants and the users don't have any restaurants, I am getting the following error:

Undefined method `restaurants' for nil:NilClass

I am checking the method is nil with following code but it doesn't work:

if !current_user.restaurants.nil?
  @restaurants = current_user.restaurants.paginate(page: params[:page], per_page: 2)
end 

How can I check if a user's restaurants is nil ?

The problem is current_user :

"undefined method `restaurants' for nil:NilClass"

current_user is nil , so it can't respond to restaurants . You need to set up current_user first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM