我正在使用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
如何解决此错误?
答案 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