Rails 序列化数据验证 [英] Rails Serialized Data Validations
问题描述
我有一个通过默认 AR 行为序列化为 YAML 的字段.它目前在一个哈希数组中,例如:
I have a field that is serialized to YAML through the default AR behavior. It is currently in an Array of Hashes for examples:
[{'name' => 'hi', 'url' => 'bye'},
{'name' => 'hi', 'url' => 'bye'},
{'name' => 'hi', 'url' => 'bye'}]
有没有办法可以在其中一些字段上使用一些基本的 AR 验证?
Is there a way I can use some basic AR validations on some of these fields?
推荐答案
是的,使用 validates_each
方法
serialize :urls
validates_each :urls do |record, attr, value|
# value is an array of hashes
# eg [{'name' => 'hi', 'url' => 'bye'}, ...]
problems = ''
if value
value.each{|name_url|
problems << "Name #{name_url['name']} is missing its url. " \
unless name_url['url']}
else
problems = 'Please supply at least one name and url'
end
record.errors.add(:urls, problems) unless problems.empty?
end
添加:您不能使用诸如 validates_length_of
之类的验证,因为验证方法不了解您的序列化字段的格式.
Added: You can't use the validations such as validates_length_of
since the validation method doesn't understand the format of your serialized field.
validates_each
方法很好,因为它使您能够编写自己的验证方法.如果合适,该方法然后可以向记录添加错误.
The validates_each
method is good since it enables you to write your own validation method. The method can then add an error to the record if appropriate.
提示:您还可以将错误添加到 record.errors 的 :base
而不是特定属性.有时,这有助于在您的视图中格式化错误消息.
Tip: You can also add an error to the :base
of record.errors rather than to the specific attribute. Sometimes this can help with the formatting of the error messages in your views.
这篇关于Rails 序列化数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!