[英]Add trackable (devise) to existing User model?
問題:我之前用最少的設計信息創建了一個用戶模型。 我看到設計有一個“可跟蹤”系統,並希望將其實施到現有模型中。 我補充說:
class AddSignInCountToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :sign_in_count, :integer
end
end
測試遷移,它不會工作。 (我還嘗試使用“默認值:0,null:false”進行此遷移,結果相同。
一旦我將“:trackable”添加到設計模型中,這些問題似乎就會發生。
我在登錄時收到此錯誤:
NoMethodError in Devise::SessionsController#create
undefined method `current_sign_in_at' for #<User:0x00007f484e5ef770>
#line with red highlight
match ? attribute_missing(match, *args, &block) : super
CMD 前幾行錯誤:
NoMethodError (undefined method `current_sign_in_at' for #<User:0x00007f484e5ef770>):
activemodel (5.2.1) lib/active_model/attribute_methods.rb:430:in `method_missing'
路線:
devise_for :users, controllers: { confirmations: 'confirmations' }
模型:
devise :database_authenticatable, :registerable,
:confirmable, :recoverable, :rememberable, :validatable, :trackable
def active_for_authentication?
super && approved
end
def inactive_message
approved? ? super : :not_approved
end
...
...
...
這是設計問題還是其他地方造成的?
問題是否也可能是因為現有模型(不知道為什么這是真的,但以防萬一),因為如果是這樣,我可以覆蓋 t 並重新創建它,因為它仍在開發中。
我想利用 Devise 提供的所有功能,並希望將其余的設計功能遷移到我的模型中。 任何人有一個或兩個建議?
Trackable
模塊不僅需要sign_in_count
屬性。 文檔中列出了所需列的完整列表如果您為其余列添加另一個遷移,一切都應該按預期工作。
回答:
(不久后在 SO: NoMethodError in Devise::SessionsController#create undefined method `current_sign_in_at' 中發現)
授予綠色檢查的答案有幫助。
我首先嘗試簡單地添加可跟蹤,沒有工作並且由於某種原因不會遷移(沒有保存錯誤)
但他們的第一個 recc 使用例如:
rake db:migrate:down VERSION=20140126101944 # use version of the user migration
rake db:migrate up VERSION=20140126101944 # use version of the user migration
我遇到的唯一問題是我添加到用戶表的所有其他遷移都沒有隨之遷移(名稱等),所以我不得不重新遷移evertyhing。
為了澄清,正如其他人所建議的那樣,我需要更多的列,而不僅僅是可跟蹤的列。 所以這可能是這里的整體問題。
要使 trackable 按預期工作,您將需要其所有必需的列。
一步一步,事情就是這樣。
首先,創建一個新的遷移文件:
rails generate migration AddDeviseTrackableColumnsToUsers
編輯新創建的文件以包含以下內容:
class AddDeviseTrackableColumnsToUsers < ActiveRecord::Migration[6.1]
def change
add_column :users, :sign_in_count, :integer, default: 0, null: false
add_column :users, :current_sign_in_at, :datetime
add_column :users, :last_sign_in_at, :datetime
add_column :users, :current_sign_in_ip, :string
add_column :users, :last_sign_in_ip, :string
end
end
運行遷移:
rails db:migrate
最后,更新您的用戶模型以激活可跟蹤:
class User < ApplicationRecord
devise :database_authenticatable, :trackable
end
它現在應該可以工作了🤗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.