英文:
Built-in Rails way of validating that a PostgreSQL Array[String] field has at least one item in it?
问题
我们有一个基本上是 PostgreSQL 数组字符串字段的字段,如下所示:
add_column :books, :tags, :string, array: true, default: []
我该如何添加验证以验证 tags
数组中至少有一个字符串,并且该字符串来自字符串枚举集合?
我在这里看到我们可以对字符串值使用 accept
,像这样:
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { accept: 'yes' }
validates :eula, acceptance: { accept: ['TRUE', 'accepted'] }
end
但是对于数组[string]字段呢?像这样是最好的选择吗?
class Book < ApplicationRecord
# tags :string is an Array
validate :tags_has_one_from_set
enum tag: {
foo: 'foo',
bar: 'bar'
}
def tags_has_one_from_set
allowed_tags = Book.tags.values
if tags.length == 0
errors.add(:tags, "Must select at least one tag")
elsif !tags.all? { |t| allowed_tags.include?(t) }
errors.add(:tags, "Must select from approved tag list")
end
end
end
在Rails中是否有任何更多的“内置”或最佳实践方式来实现这一点?
英文:
We have a PostgreSQL array string field basically like:
add_column :books, :tags, :string, array: true, default: []
How can I add a validation to verify that that tags
array has at least 1 string in it, and that the string is from an enum set of strings?
I see we have accept
on string values, like this:
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { accept: 'yes' }
validates :eula, acceptance: { accept: ['TRUE', 'accepted'] }
end
But what about on array[string] fields? Is something like this my best option?
class Book < ApplicationRecord
# tags :string is an Array
validate :tags_has_one_from_set
enum tag: {
foo: 'foo',
bar: 'bar'
}
def tags_has_one_from_set
allowed_tags = Book.tags.values
if tags.length == 0
errors.add(:tags, "Must select at least one tag")
elsif !tags.all? { |t| allowed_tags.include?(t) }
errors.add(:tags, "Must select from approved tag list")
end
end
end
Is there any more "built-in" or best-practice sort of way of doing this in Rails?
答案1
得分: 1
你应该能够使用内置的 length
和 inclusion
验证器:
validates :tags,
length: { minimum: 1, message: "必须至少有一个标签" },
inclusion: { in: tags.values, message: "必须从以下选项中选择: #{tags.values.join(", ")}" }
英文:
You should be able to use the built in length
and inclusion
validators:
validates :tags,
length: { minimum: 1, message: "must have at least one tag" },
inclusion: { in: tags.values, message: "must be selected from: #{tags.values.join ", "}" }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论