在設置如何顯示誰使用導軌訪問了我的應用上的用戶配置文件時遇到了一個簡單問題?我正在關注這個問題上接受的答案 - 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
你應該使用'before_action:create_visit,只有:[:show]'否則數字將會太高。 –