繁体   English   中英

将可跟踪(设计)添加到现有用户模型?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM