繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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