Rails 4、SQ Lite 3: NoMethodError - 未定义方法: nil:NilClass
Rails 4, SQ Lite 3: NoMethodError - undefined method: nil:NilClass
我创建了一个通知模型,其中 belongs_to
一个用户(设计)和每个用户 has_many
个通知。
但是我无法在我的应用程序控制器或任何其他控制器中获得通知:
def notifications
@notifications = Notification.where(user_id: current_user.id).order('created_at desc')
end
我似乎总是得到 nil
作为对象。
例如:
食谱/搜索视图 (views/items/search.html.haml):
- if @notifications.exists?
给我这个错误:
NoMethodError
undefined method `exists?' for nil:NilClass
在我的控制台中,我可以通过以下方式获取通知:
Notification.where(user_id: 3)
在此先感谢您的帮助!
拼写错误- if @notifcations.exists?
试试- if @notifications.exists?
我建议您将代码更改为
在user.rb
def ordered_notifications
notifications.order(created_at: :desc)
end
在您看来
- if @current_user.ordered_notifications.exists?
尝试:
- if @notifications.any?
那么你不会得到 NoMethodError 如果它是空的它会被视为 false
我创建了一个通知模型,其中 belongs_to
一个用户(设计)和每个用户 has_many
个通知。
但是我无法在我的应用程序控制器或任何其他控制器中获得通知:
def notifications
@notifications = Notification.where(user_id: current_user.id).order('created_at desc')
end
我似乎总是得到 nil
作为对象。
例如:
食谱/搜索视图 (views/items/search.html.haml):
- if @notifications.exists?
给我这个错误:
NoMethodError
undefined method `exists?' for nil:NilClass
在我的控制台中,我可以通过以下方式获取通知:
Notification.where(user_id: 3)
在此先感谢您的帮助!
拼写错误- if @notifcations.exists?
试试- if @notifications.exists?
我建议您将代码更改为
在user.rb
def ordered_notifications
notifications.order(created_at: :desc)
end
在您看来
- if @current_user.ordered_notifications.exists?
尝试:
- if @notifications.any?
那么你不会得到 NoMethodError 如果它是空的它会被视为 false