【发布时间】:2011-06-15 19:57:02
【问题描述】:
有什么方法可以验证 Rails 中的单个属性?
类似:
ac_object.valid?(attribute_name)
【问题讨论】:
标签: ruby-on-rails validation rails-activerecord
有什么方法可以验证 Rails 中的单个属性?
类似:
ac_object.valid?(attribute_name)
【问题讨论】:
标签: ruby-on-rails validation rails-activerecord
您可以在模型中实现自己的方法。像这样的
def valid_attribute?(attribute_name)
self.valid?
self.errors[attribute_name].blank?
end
或添加到ActiveRecord::Base
【讨论】:
有时会有非常昂贵的验证(例如,需要执行数据库查询的验证)。在这种情况下,您需要避免使用valid?,因为它的功能远远超出您的需要。
有一个替代解决方案。可以使用ActiveModel::Validations的validators_on方法。
validators_on(*attributes) 公开
列出所有用于验证特定的验证器 属性。
据此您可以手动验证所需的属性
例如我们只想验证Post 的title:
class Post < ActiveRecord::Base
validates :body, caps_off: true
validates :body, no_swearing: true
validates :body, spell_check_ok: true
validates presence_of: :title
validates length_of: :title, minimum: 30
end
其中no_swearing 和spell_check_ok 是极其昂贵的复杂方法。
我们可以做到以下几点:
def validate_title(a_title)
Post.validators_on(:title).each do |validator|
validator.validate_each(self, :title, a_title)
end
end
这将仅验证 title 属性而不调用任何其他验证。
p = Post.new
p.validate_title("")
p.errors.messages
#=> {:title => ["title can not be empty"]
我不完全相信我们应该安全地使用validators_on,所以我会考虑在validates_title 中以理智的方式处理异常。
【讨论】:
self.class.validators_on并将属性名称作为参数使其更易于重用。
我最终以@xlembouras 的回答为基础,并将此方法添加到我的ApplicationRecord:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def valid_attributes?(*attributes)
attributes.each do |attribute|
self.class.validators_on(attribute).each do |validator|
validator.validate_each(self, attribute, send(attribute))
end
end
errors.none?
end
end
然后我可以在控制器中做这样的事情:
if @post.valid_attributes?(:title, :date)
render :post_preview
else
render :new
end
【讨论】:
errors.none? 可能涉及其他错误(例如,如果此函数以前针对不同的属性运行)。可能的改进:如果您只关心布尔标志而不关心实际错误,您可以考虑在循环中返回:return false unless self.errors[attribute].blank?。我认为self[attribute] 比send(attribute) 更好,但这只是个人喜好。您也可以将其提取到关注点,而不是将其放在父类中(同样,偏好)。
errors 之前切片none?:@987654330 @。这不是 ActiveModel::Validations 处理事情的方式。 // 无论如何,使用[] 访问属性与使用send 不同。后者将调用访问器方法,这是您想要的 99/100。此外,短路意味着并非所有错误都可用于视图呈现。这可能是不可取的。
基于@coreyward 的回答,我还添加了validate_attributes! 方法:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def valid_attributes?(*attributes)
attributes.each do |attribute|
self.class.validators_on(attribute).each do |validator|
validator.validate_each(self, attribute, send(attribute))
end
end
errors.none?
end
def validate_attributes!(*attributes)
valid_attributes?(*attributes) || raise(ActiveModel::ValidationError.new(self))
end
end
【讨论】: