2017-08-04 69 views
0

我在導航欄中顯示通知,它在大約一半的頁面上工作。 另一方面,我得到了一個零: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,我確定我必須定義它,因爲它在其他地方起作用,所以它很奇怪。

+0

你在哪裏設置'@ current_user'?你可以顯示該代碼嗎?同時顯示完整的錯誤日誌和控制器代碼。 – Gerry

+0

你的控制器與頁面出錯有什麼關係?我猜測@current_user沒有正確定義。 – Belder

+0

@BrandonElder這也是我的猜想。這是一個佈局,但我認爲它來自應用程序控制器。奇怪的是,它不在那裏,我確實使用了幾個寶石,不知道它們是否在某處定義。我擔心的是,當我定義它的時候,它會在我用current_user工作的所有其他頁面中使用type來混淆。 – MaxLeoTony

回答

1

你需要設置@current_user變量每次你想渲染你的導航欄。僅僅因爲你有一個User模型並不意味着@current_user變量在任何特定時間點都有任何值。這是您設置變量的工作。 Rails很聰明,但不是那麼聰明。

通常,您將在controller中設置@current_user變量。有些人喜歡爲這樣的事情做一個before_action。就我個人而言,我沒有。您可以在您的ApplicationController中設置您的before_action,然後您的@current_user變量將隨處可用。

在Rails 4,這可能看起來像:

class ApplicationController < ActionController::Base 
    before_action :set_user 

    def index()  do_action_with_presentation    end 
    def new()  do_action_with_presentation    end 
    def create() do_cancellable_action_with_redirect  end 
    def show()  do_action_with_presentation    end 
    def edit()  do_action_with_presentation    end 
    def update() do_action_with_presentation    end 
    def delete() do_action_with_presentation    end 

private 

    def set_user 
    @current_user = User.find_by(something: :clever) 
    end 

end 

你可以忽略我的奇特的REST動作。他們,呃,特別。

相關問題