【发布时间】:2015-12-02 04:18:37
【问题描述】:
我正在为存储键/值对的表构建 ActiveRecord 模型
例子-
|------------------------------|
| KEY | VALUE |
|----------|-------------------|
| LOCATION | San Francisco, CA |
| TITLE | Manager |
| LOCATION | New York City, NY |
|------------------------------|
这是模型 -
class CompanyEnum < ActiveRecord::Base
KEYS = [:title, :department, :location]
KEYS_ENUM = KEYS.map(&:to_s).map(&:upcase)
# `key` column must be one of the above - LOCATION, DEPARTMENT, or TITLE
validates(:key, inclusion: KEYS_ENUM, allow_nil: false)
# `value` can be anything, but must be unique for a given key (ignoring case)
validates(
:value,
uniqueness: { scope: :key, case_sensitive: false },
allow_nil: false
)
end
我正在使用shoulda matchers 为这些验证编写规范。所以在我的规范文件中,我有以下两个规范 -
describe "validations" do
it { should_not allow_value(nil).for(:key) }
it { should_not allow_value(nil).for(:value) }
end
我的问题是:key 的第一次验证通过,但:value 的第二次验证失败。根据模型定义,两者都使用相同的 allow_nil: false 选项。
1) CompanyEnum validations value should not allow value to be set to nil
Failure/Error: it { should_not allow_value(nil).for(:value) }
Expected errors when value is set to nil,
got no errors
# ./spec/models/company_enum_spec.rb:13:in `block (4 levels) in <top (required)>'
# ./spec/support/analytics.rb:4:in `block (2 levels) in <top (required)>'
将allow_nil: false 与uniqueness: 和scope: optoins 一起使用是否有任何逻辑问题?或者它与我命名实际列 :key 和 :value 有什么关系(因为这些似乎通用到与其他一些方法冲突)?
谢谢!
【问题讨论】:
-
为什么不直接使用存在验证器呢?我认为它因为范围条款而搞砸了。也只是一个性能提及,但您可能希望冻结每个字符串和键枚举的数组,否则它们是使用每个模型实例创建的。
标签: ruby-on-rails activerecord shoulda