gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:24:02 26 4
gpt4 key购买 nike

嗨,我的模型中有一个数组列:

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) }

Rails Documentation有关 inclusion 的更多用法和示例.

更新

由于 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

关于ruby-on-rails - 如何验证在 rails 中包含数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com