是否可以使用密码表中的每个字段轻松设置Devise gem,密码表使用属于User模型的密码模型(只有email
字段)进行映射?
换句话说,这是我想要的模型设计的图画:
+-------+
| User |
+-------+
| email |
+-------+
^ (have one)
|
| (belongs to)
+------------------------+
| Password |
+------------------------+
| encrypted_password |
| reset_password_token |
| reset_password_sent_at |
| sign_in_count |
| ... |
+------------------------+
Devise wiki非常完整,但没有任何相关信息。
答案 0 :(得分:0)
是的,有一个解决方法,包括重写Devise内部方法(这是一个不推荐的东西)。
但是,我没有很好地测试它(我只创建了一个用户并尝试登录),这可能会在Devise中引入一些错误和不必要的行为。因此,请确保在此代码发布到生产之前,您的应用程序已经过充分测试。
数据库可验证模块的解决方案包括:
撰写迁移
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :email
t.timestamps
end
create_table :passwords, :force => true do |t|
t.integer :user_id
t.string :encrypted_password, :null => false, :default => ""
end
end
end
创建一个指向delegate
的{{1}}。
password_record#encrypted_password
添加到accepts_nested_attributes_for
password_record
属性创建一个setter(Devise使用此属性)你的模特应该是这样的:
encrypted_password
我用这个创建了一个用户:
class User < ActiveRecord::Base
devise :database_authenticatable
has_one :password_record, :class_name => "Password", :foreign_key => "user_id"
delegate :encrypted_password, :to => :password_record
accepts_nested_attributes_for :password_record
def encrypted_password=(encrypted_password)
self.password_record.encrypted_password = encrypted_password
end
attr_accessible :email, :password, :password_confirmation, :remember_me
end
class Password < ActiveRecord::Base
belongs_to :user
end
我测试了x = User.new
x.password_record = Password.new
x.password = "123456"
x.email = "a@b.com"
x.save
动作并且它有效。
您可以使用带有nested attributes的sign_up表单进行创建。要检查如何为其他模块执行相同的操作,请查看Devise源代码()并查看它使用的属性及其工作原理(https://github.com/plataformatec/devise/tree/master/lib/devise/models)。