我在導航欄中顯示通知,它在大約一半的頁面上工作。 另一方面,我得到了一個零:NilClass錯誤,我以前已經處理過。但我的印象是@ current_user.notifications.each足夠了,因爲用戶和通知模型。 顯然不是。與通知未定義的方法`通知'爲零:NilClass
<div class="dropdown nav-button notifications-button hidden-sm-down">
<a class="btn btn-secondary dropdown-toggle" href="#" id="notifications-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i id="notificationsIcon" class="fa fa-bell-o" aria-hidden="true"></i>
</a>
<div class="dropdown-menu notification-dropdown-menu" aria-labelledby="notifications-dropdown">
<h6 class="dropdown-header">Notifications</h6>
<div id="notificationsContainer" class="notifications-container">
<% @current_user.notifications.each do |notification| %>
<% if notification.notice_type == "post" %>
<%= link_to "Someone commented on your post", notification.post %>
<% end %>
<br>
<% end %>
<hr>
<%= link_to "All Notifications", notifications_path %>
<br>
<br>
</div>
</div>
</div>
用戶模型
導航欄部分包括
has_many :notifications, dependent: :destroy
通知模型
class Notification < ApplicationRecord
belongs_to :notified_by, class_name: 'User'
belongs_to :user
belongs_to :post, optional: true
validates :user_id,
:notified_by_id,
:identifier,
:notice_type,
presence: true
end
我曾與本教程(https://www.devwalks.com/lets-build-instagram-part-6-notifications/),但改變了一些東西,一路上。例如,我不想使用HAML。 不管怎樣,爲什麼它不認可current_user,我確定我必須定義它,因爲它在其他地方起作用,所以它很奇怪。
你在哪裏設置'@ current_user'?你可以顯示該代碼嗎?同時顯示完整的錯誤日誌和控制器代碼。 – Gerry
你的控制器與頁面出錯有什麼關係?我猜測@current_user沒有正確定義。 – Belder
@BrandonElder這也是我的猜想。這是一個佈局,但我認爲它來自應用程序控制器。奇怪的是,它不在那裏,我確實使用了幾個寶石,不知道它們是否在某處定義。我擔心的是,當我定義它的時候,它會在我用current_user工作的所有其他頁面中使用type來混淆。 – MaxLeoTony