简体   繁体   English

如何验证在 rails 中包含数组内容

[英]How to validate inclusion of array content in rails

Hi I have an array column in my model:嗨,我的模型中有一个数组列:

t.text :sphare, array: true, default: []

And I want to validate that it includes only the elements from the list ("Good", "Bad", "Neutral")我想验证它是否只包含列表中的元素(“好”、“坏”、“中性”)

My first try was:我的第一次尝试是:

 validates_inclusion_of :sphare, in: [ ["Good"], ["Bad"], ["Neutral"] ]

But when I wanted to create objects with more then one value in sphare ex(["Good", "Bad"] the validator cut it to just ["Good"].但是,当我想在 sphare ex(["Good", "Bad"] 中创建具有多个值的对象时,验证器将其剪切为 ["Good"]。

My question is:我的问题是:

How to write a validation that will check only the values of the passed array, without comparing it to fix examples?如何编写仅检查传递数组的值而不将其与修复示例进行比较的验证?

Edit added part of my FactoryGirl and test that failds:编辑添加了我的 FactoryGirl 的一部分并测试失败:

Part of my FactoryGirl:我的 FactoryGirl 的一部分:

sphare ["Good", "Bad"]

and my rspec test:和我的 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  

Do it this way:这样做:

validates :sphare, inclusion: { in: ["Good", "Bad", "Neutral"] }

or, you can be fancy by using the short form of creating the array of strings: %w(Good Bad Neutral) :或者,您可以使用创建字符串数组的简短形式: %w(Good Bad Neutral)

validates :sphare, inclusion: { in: %w(Good Bad Neutral) }

See the Rails Documentation for more usage and example of inclusion .有关更多用法和inclusion示例,请参阅Rails 文档

Update更新

As the Rails built-in validator does not fit your requirement, you can add a custom validator in your model like following:由于 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

You can implement your own ArrayInclusionValidator :您可以实现自己的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

In the model it looks like this:在模型中它看起来像这样:

# app/models/model.rb
class YourModel < ApplicationRecord
  ALLOWED_TYPES = %w[one two three]
  validates :type_of_anything, array_inclusion: { in: ALLOWED_TYPES }
end

Examples can be found here:示例可以在这里找到:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM