Gugubaight Gugubaight - 1 month ago 15
Ruby Question

Rails 4, SQ Lite 3: NoMethodError - undefined method: nil:NilClass

I've created a Notification Model which

belongs_to
a User (Devise) and each User
has_many
Notifications.

However I somehow can't get the Notifications in my Applications Controller or any other Controller:

def notifications
@notifications = Notification.where(user_id: current_user.id).order('created_at desc')
end


I always seem to get
nil
as Object.

For example:

Recipes / Search View (views/items/search.html.haml):

- if @notifications.exists?


gives me this error:

NoMethodError
undefined method `exists?' for nil:NilClass


In my console I can get the Notifications with the following:

Notification.where(user_id: 3)


Thanks in advance for any help!

Answer

There is spelling mistake in - if @notifcations.exists? try - if @notifications.exists?

I suggest you change your code to

In user.rb

def ordered_notifications
   notifications.order(created_at: :desc)
end

In your view

- if @current_user.ordered_notifications.exists?