2016-10-17 7 views
0

通知モデルを作成しました。belongs_toユーザー(Devise)と各ユーザーhas_many通知。
しかし、私は何とか自分のアプリケーションのコントローラや他のコントローラでの通知を取得することはできません。Rails 4、SQ Lite 3:NoMethodError - 未定義メソッド:なし:NilClass

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

私はいつもObjectとしてnilを得るように見えます。
レシピ/検索ビュー(ビュー/アイテム/ search.html.haml):たとえば

私のコンソールIで

NoMethodError 
undefined method `exists?' for nil:NilClass 

- if @notifications.exists? 

は私に、このエラーが発生します次のように通知を受け取ることができます:

Notification.where(user_id: 3) 

事前にお手伝いをしていただきありがとうございます!

+0

として扱われます - ?@ notifcations.exists場合' notifications.html.erb/HAMLでこのコードの存在があります? – dnsh

+0

あなたの通知メソッドでは、current_user.notificationsはnilです。何も@notificationsに割り当てられないので、nil:NilClassエラーが発生します。 – Navin

+0

'〜notifcations.exists? 'にスペルミスがあります。' - もし@ notifications.existsなら '? – dnsh

答えて

1

は、スペルの間違い- if @notifcations.exists?で試すあり- if @notifications.exists?

私はあなたのビューでuser.rb

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

にコードを変更示唆

- if @current_user.ordered_notifications.exists? 
+0

ありがとうございました。残念ながらそれは問題を解決しません、私はまだそのエラーを取得します... – Gugubaight

+0

@ Gugubaightビューファイルのファイル名は何ですか? – dnsh

+0

search.html.haml – Gugubaight

0

してみてください。

- if @notifications.any? 

次に、あなたはNoMethodErrorを取得することはありませんし、それが空の場合、それは `偽

関連する問題