[英]How can I use Rails Validations to allow and attribute variable to be one of two values?
For a project, I need the categories attribute of the Post class to be either "Fiction" or "Non-Fiction."对于一个项目,我需要 Post class 的类别属性为“小说”或“非小说”。 I attempted the following syntax...
我尝试了以下语法...
class CategoryValidator < ActiveModel::Validator
def validate(record)
unless (record.category == "Fiction" || "Non-Fiction")
record.errors[:category] << "Must be valid category"
binding.pry
end
end
end
but it never hit the binding.pry line, meaning it never hit "until" block, even when I entered purposefully wrong answers.但它从来没有打到 binding.pry 行,这意味着它从来没有打到“直到”块,即使我故意输入了错误的答案。 What would the proper syntax for the #validate method be?
#validate 方法的正确语法是什么?
Your condition to check if the category is either 'Fiction'
or 'Non-Fiction'
isn't right.您检查类别是
'Fiction'
还是'Non-Fiction'
的条件不正确。
(record.category == "Fiction" || "Non-Fiction")
is evaluated as (record.category == "Fiction") || "Non-Fiction"
(record.category == "Fiction" || "Non-Fiction")
被评估为(record.category == "Fiction") || "Non-Fiction"
(record.category == "Fiction") || "Non-Fiction"
since ==
has higher precedence than ||
(record.category == "Fiction") || "Non-Fiction"
,因为==
的优先级高于||
. . As a result, the expression will always return
"Non-Fiction"
which is truthy.因此,表达式将始终返回真实
"Non-Fiction"
。 That's why your code never got to the binding.pry
line even when the category wasn't "valid".这就是为什么即使类别不是“有效”,您的代码也永远不会到达
binding.pry
行的原因。
def validate(record)
unless %w(Fiction Non-Fiction).include?(record.category)
record.errors[:category] << "Must be valid category"
end
end
A custom validator is an overkill for this use-case.自定义验证器对于这个用例来说太过分了。 You can use
inclusion
to add this validation.您可以使用
inclusion
来添加此验证。
validates :category, inclusion: {
in: %w(Fiction Non-Fiction),
message: 'must be either Fiction or Non-Fiction'
}
I hate myself, such a simple fix and I got it我讨厌自己,这么简单的解决方法,我明白了
class CategoryValidator < ActiveModel::Validator
def validate(record)
unless (record.category == "Fiction" || record.category == "Non-Fiction")
record.errors[:category] << "Must be valid category"
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.