将数据导入用户模型时出错

时间:2017-11-01 13:30:30

标签: ruby-on-rails ruby-on-rails-5

我正在使用devise gem进行用户会话操作。我想在管理面板中将数据导入用户模型。

Ruby版本:2.4.1p111

Rails版本:Rails 5.1.4

管理面板gem:activeadmin

管理面板导入gem:active_admin_import

管理员/ user.rb

ActiveAdmin.register User do active_admin_import validate: true, template_object: ActiveAdminImport::Model.new( hint: "Dosyanızda veriler belirtilen başlıklar altında olmalıdır: 'email', 'identity_no', 'password', 'password_confirmation'", csv_headers: ['email', 'identity_no', 'password', 'password_confirmation'] ) permit_params :email, :identity_no, :password, :password_confirmation .... ... end

模型/ user.rb

class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_one :profile, dependent: :destroy has_many :graduations, dependent: :destroy has_many :works, dependent: :destroy validates :identity_no, presence: true ... ... end

我收到了错误消息: can't write unknown attribute password

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

<强>原因

设计创建encrypted_password数据库字段,而不是password字段,并覆盖password=方法进行加密,然后将加密的方法分配给encrypted_password

active_admin_import会直接导入,因此不会通过password=方法,因此会发生错误

<强>解决方案

使用before_batch_import模拟加密过程并将加密密码分配给encrypted_password字段。不需要password_confirmation。例如:

active_admin_import validate: false,
  before_batch_import: proc { |import|
    import.csv_lines.length.times do |i|
      import.csv_lines[i][2] = User.new(password: import.csv_lines[i][2]).encrypted_password
    end
  },
  template_object: ActiveAdminImport::Model.new(
    csv_headers: ['email', 'identity_no', 'encrypted_password']
  ),
  timestamps: true