【问题标题】:Password not getting stored for a model with same table, but different structure没有为具有相同表但结构不同的模型存储密码
【发布时间】:2017-04-26 13:21:27
【问题描述】:

我有一个名为 User 的模型,它具有 first_name、last_name 和 password 属性。它正在使用设计。现在我想要另一个名为 Receptionist 的模型,它共享同一个用户表。用户可以添加接待员。

这是我的代码

 class Receptionist < ApplicationRecord
    attr_accessor :password
    attr_accessor :password_confirmation
    self.table_name = "users"
    belongs_to :user, :class_name => 'User', :foreign_key => 'user_id' #source: :doctor
 end

     class User < ApplicationRecord
        devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable
       has_many :receptionists, :class_name => 'Receptionist', :foreign_key => 'user_id'
       accepts_nested_attributes_for :receptionists, allow_destroy: true
     end

在更新方法中——我有这个

user = User.new(get_params)
user.save


  def get_params
    params.require(:user).permit(:first_name, :last_name,
         receptionists_attributes: [:first_name, :last_name, :email, :password, :password_confirmation, :_destroy]
      )
 end

这里是api调用

{
    "auth_token": "TMERW-fhNroA9La9iUSX",
    "user": {
        "receptionists_attributes": {
            "0": {
                "first_name": "reception 1",
                "last_name": "g",
                "email": "xx@gmail.com",
                "password": "xxxxx",
                "password_confirmation": "xxxx"

            }
        }
    }
}

现在接收者的记录正在被保存,除了密码。密码被存储为零。谁能告诉我哪里出错了

【问题讨论】:

  • 删除attr_accessor :passwordattr_accessor :password_confirmation
  • 然后出现未知属性密码错误
  • 那么密码不在数据库中
  • user 表通常没有password 列,因为您永远不应该以明文形式存储密码
  • 好吧,你是对的..那么密码存储在哪里?

标签: ruby-on-rails devise


【解决方案1】:

devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable 添加到Receptionist 模型。

你需要删除

attr_accessor :password
attr_accessor :password_confirmation

因为它将覆盖设计的方法来设置encrypted_password。而attrattr_accessor 生成的attr 不会保存到数据库,所以当它超出生命周期时,它会变成nil

并且devise不会直接将原始密码保存到数据库,它会将password加密并保存在encrypted_password列中,因此您无法提取password,您只能验证是否password 是有效的,比如

user.valid_password?('12345678')

加密算法请查看Rails Devise, how to unencrypt a password?

【讨论】:

  • 也将devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable 添加到Receptionist 模型
  • 请在您的答案中添加此评论..我只是写相同的答案..我想通了..还是谢谢..
  • @gates 虽然它工作正常,但不得不说,2 模型使用相同的表,它似乎有线。您可以检查acts_as_tree 或其他增强activerecord 的gem,想想您是否真的必须这样做。或者至少有模型覆盖。
猜你喜欢
  • 1970-01-01
  • 2021-11-24
  • 2016-02-23
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 2022-08-05
  • 1970-01-01
相关资源
最近更新 更多