我正在努力让Clearance与AWS Dynamo一起作为后端商店。我遇到的问题是我无法清除不执行电子邮件唯一性验证,因为它无法通过SQL查询执行标准的ActiveRecord唯一性验证而无法执行此操作
根据the comments in the code,我应该可以让我的User
对象返回email_optional?
true
,这应该会禁用电子邮件的唯一性验证。所以我有:
class User < ApplicationRecord
include Dynamoid::Document
include Clearance::User
field :name
field :email
def email_optional?
puts 'yes, email is optional'
true
end
end
但是,当我尝试创建用户时,我收到错误,而且更重要的是,puts
未执行:
$ rails c
Running via Spring preloader in process 18665
Loading development environment (Rails 5.1.3)
irb(main):001:0> u = User.new(name: 'ijd', email: 'ian@fu.bar', password: 'test')
ActiveRecord::StatementInvalid: Could not find table 'editor_development_users'
from (irb):1
更新:来自@spickermann的回复提醒我,我应该注意到我也尝试过没有子类化ActiveRecord::Base
(通过ApplicationRecord
)。它给出了一个不同的错误:
class User
include Dynamoid::Document
....
irb(main):002:0> reload!
Reloading...
=> true
irb(main):003:0> u = User.new(name: 'ijd', email: 'ian@fu.bar', password: 'test')
ArgumentError: Unknown validator: 'UniquenessValidator'
from app/models/user.rb:4:in `include'
from app/models/user.rb:4:in `<class:User>'
from app/models/user.rb:2:in `<top (required)>'
from (irb):3
答案 0 :(得分:1)
User.new
不会触发验证。因此,错误无法连接到验证本身。
目前,您的User
模型属于两者:ActiveRecord::Base
的子类,其行为类似于Dynamoid::Document
。
class User < ApplicationRecord
include Dynamoid::Document
# ...
end
初始化实例时, ActiveRecord::Base
从数据库中读取表定义。这会导致您的异常,因为该表不存在。只需从ApplicationRecord
删除继承。
class User
include Dynamoid::Document
# ...
end
删除继承时的第二个问题更复杂。通常,当您想要验证不从include ActiveModel::Validations
继承的模型时,我建议仅ActiveRecord::Base
。但UniquenessValidator
中ActiveModel::Validations
未定义,ActiveRecord::Validations
Clearance
中定义ActiveRecord::Base
。这使UniquenessValidator
与不从class User
include Dynamoid::Document
class UniquenessValidator
def initialize(_options); end
def def validate_each(_record, _attribute, _value); end
end
# ...
end
继承的模型不兼容。
我可能会定义anton
的虚拟实现作为解决方法:
'Moneyback'