2017-01-30 30 views
0

在設置如何顯示誰使用導軌訪問了我的應用上的用戶配置文件時遇到了一個簡單問題?我正在關注這個問題上接受的答案 - How to show who has visited your profile?,但遇到了一個讓我有點困惑的錯誤。我列出我收到的錯誤和我下面的相關代碼:如何顯示誰在Rails中訪問過用戶的個人資料?

兩個錯誤出現在我的用戶控制器

ERROR1:未定義的方法visits' for nil:NilClass Error2: can't write unknown attribute visitor_id` >>每當我訪問用戶的個人資料

用戶控制器

class UsersController < ApplicationController 
before_action :set_user, only: [:show, :edit, :update, :destroy, :share, :follow] 
before_action :create_visit 

def show 
@user = User.find(params[:id]) 
@visitprofiles = current_user.visitors.where('created_at > ?', 1.month.ago) 
end 
private 

def set_user 
    @user = User.find(params[:id]) 
end 

def create_visit 
@user.visits.create(visitor: current_user) 
end 

User.rb

class User < ApplicationRecord 
# Include default devise modules. Others available are: 
# :confirmable, :lockable, :timeoutable and :omniauthable 
devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook] 




has_many :visits 
has_many :visitors, through: :visits 

Visit.rb

class Visit < ApplicationRecord 
belongs_to :user 
belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id' 
end 
+0

你應該使用'before_action:create_visit,只有:[:show]'否則數字將會太高。 –

回答

2

因爲你@usernil

您有before_action :set_user,但它在create_user之前未被調用。您的@user沒有設置,因此,它是零。調試

兩種寶石你應該所示,其中的代碼是打破。 Better errorsBinding or callers是我發現用於快速調試Rails應用程序的兩個寶石。

另一個問題與您的代碼

set_user brefore show,和你有相同的邏輯來尋找您的show方法的用戶。這不是乾的。

+0

愛德蒙非常感謝你的回覆,我跟你一下,我將如何着手解決它。我需要更改user.rb嗎? – Omar

+0

@Omar在'create_visit'之前你需要'set_user'。只需在'before_action:set_user'中將'create_visit'添加到'only:'數組中即可。 –

+0

埃德蒙得到了它,所以它不會再給我一個錯誤,因爲我像下面這樣做了以下建議:''before_action:set_user,只:[:show,:edit,:update,:destroy,:share,:follow ,:create_visit]''。現在根據我的觀點來計算訪客人數。我應該在控制器中做以下事情 - 「'@visitprofiles = current_user.visitors.where('created_at>?',1.month.ago)''並且在我的視圖中簡單地執行''<%= @ visitprofiles.count%> ''? – Omar

相關問題