Rails ActiveRecord:验证单个属性
有什么方法可以验证 ActiveRecord 中的单个属性吗?
像这样的东西:
ac_object.valid?(attribute_name)
Is there any way I can validate a single attribute in ActiveRecord?
Something like:
ac_object.valid?(attribute_name)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有时有些验证非常昂贵(例如需要执行数据库查询的验证)。在这种情况下,您需要避免使用
valid?
因为它所做的事情远远超出了您的需要。还有一个替代解决方案。您可以使用
ActiveModel::Validations< 的
validators_on
方法/代码>。根据它,您可以手动验证您想要的属性,
例如我们只想验证
Post
的title
:其中
no_swearing
和spell_check_ok
是极其昂贵的复杂方法。我们可以执行以下操作:
这将仅验证标题属性,而不调用任何其他验证。
请注意,
我并不完全相信我们应该安全地使用
validators_on
,因此我会考虑在validates_title
中以合理的方式处理异常。Sometimes there are validations that are quite expensive (e.g. validations that need to perform database queries). In that case you need to avoid using
valid?
because it simply does a lot more than you need.There is an alternative solution. You can use the
validators_on
method ofActiveModel::Validations
.according to which you can manually validate for the attributes you want
e.g. we only want to validate the
title
ofPost
:Where
no_swearing
andspell_check_ok
are complex methods that are extremely expensive.We can do the following:
which will validate only the title attribute without invoking any other validations.
note
I am not completely confident that we are supposed to use
validators_on
safely so I would consider handling an exception in a sane way invalidates_title
.您可以在模型中实现自己的方法。像这样的东西
或者将其添加到
ActiveRecord::Base
You can implement your own method in your model. Something like this
Or add it to
ActiveRecord::Base
我最终以 @xlembouras 的答案为基础,并将此方法添加到我的
ApplicationRecord
中:然后我可以在控制器中执行类似的操作:
I wound up building on @xlembouras's answer and added this method to my
ApplicationRecord
:Then I can do stuff like this in a controller:
在 @coreyward 的回答的基础上,我还添加了一个
validate_attributes!
方法:Building on @coreyward's answer, I also added a
validate_attributes!
method:由于
validator.validate_each
是私有方法,我在使用其他解决方案时遇到了问题。下面是在 Rails 6 下运行的代码片段:
I had problems with other solutions due to
validator.validate_each
being a private method.Here's a snippet that's working under Rails 6: