[英]How to validate inclusion of array content in rails
嗨,我的模型中有一個數組列:
t.text :sphare, array: true, default: []
我想驗證它是否只包含列表中的元素(“好”、“壞”、“中性”)
我的第一次嘗試是:
validates_inclusion_of :sphare, in: [ ["Good"], ["Bad"], ["Neutral"] ]
但是,當我想在 sphare ex(["Good", "Bad"] 中創建具有多個值的對象時,驗證器將其剪切為 ["Good"]。
我的問題是:
如何編寫僅檢查傳遞數組的值而不將其與修復示例進行比較的驗證?
編輯添加了我的 FactoryGirl 的一部分並測試失敗:
我的 FactoryGirl 的一部分:
sphare ["Good", "Bad"]
和我的 rspec 測試:
it "is not valid with wrong sphare" do
expect(build(:skill, sphare: ["Alibaba"])).to_not be_valid
end
it "is valid with proper sphare" do
proper_sphare = ["Good", "Bad", "Neutral"]
expect(build(:skill, sphare: [proper_sphare.sample])).to be_valid
end
這樣做:
validates :sphare, inclusion: { in: ["Good", "Bad", "Neutral"] }
或者,您可以使用創建字符串數組的簡短形式: %w(Good Bad Neutral)
:
validates :sphare, inclusion: { in: %w(Good Bad Neutral) }
有關更多用法和inclusion
示例,請參閱Rails 文檔。
由於 Rails 內置驗證器不符合您的要求,您可以在模型中添加自定義驗證器,如下所示:
validate :correct_sphare_types
private
def correct_sphare_types
if self.sphare.blank?
errors.add(:sphare, "sphare is blank/invalid")
elsif self.sphare.detect { |s| !(%w(Good Bad Neutral).include? s) }
errors.add(:sphare, "sphare is invalid")
end
end
您可以實現自己的ArrayInclusionValidator
:
# app/validators/array_inclusion_validator.rb
class ArrayInclusionValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# your code here
record.errors.add(attribute, "#{attribute_name} is not included in the list")
end
end
在模型中它看起來像這樣:
# app/models/model.rb
class YourModel < ApplicationRecord
ALLOWED_TYPES = %w[one two three]
validates :type_of_anything, array_inclusion: { in: ALLOWED_TYPES }
end
示例可以在這里找到:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.