ruby-on-rails - 如何判断哪些关联模型未通过我的 ActiveRecord 验证?
问题描述
假设我有以下型号:
class Race < ApplicationRecord
has_many :horses
end
class Horse < ApplicationRecord
belongs_to :race
validates :name, presence: true
end
现在使用我的 REST API,我正在创建一个Race
对象并关联多匹马。其中一匹马未能通过验证,这增加了错误。
添加错误意味着向errors.details
and中添加条目errors.messages
,其中errors
是Race
模型的一个字段。这两个字段都是散列,分别horses.name
作为键和错误和错误消息的详细信息作为值。
我正在寻找一种方法来查找哪些关联Horse
模型未通过验证,以便我可以提供全面的错误消息。一个引用、id 甚至一个索引就足够了。
解决方案
race = Race.create race_params
race.errors.messages
=> {'horses.name' => ['Can't be blank']}
race.horces[0].errors.messages
=> {'name' => ['Can't be blank']}
要获取错误记录,只需过滤 race.horses
with_error = race.horses.select{|h| h.errors.messages.present?}
index = race.horses.index( with_error[0] )
推荐阅读
- php - 在 PHP 中计算二维数组的列数
- java - 获取无效数字异常:ORA-01722:在金额字段中执行带有十进制值的查询时无效数字
- c# - 如何在xamarin的mainactivity中更改android下载文件的路径?
- angular - Cloudinary 与 Angular
- python - 值:xx 必须是
使用 EmbeddedField 和 ModelForm - json - Swift - 使用大 JSON 使 EXC_BAD_ACCESS JSONDecoder 崩溃
- xmobar - 在从 xmobar 的 MultiCpu 获得的每个值旁边显示百分比符号
- java - 在java中获取实体值的最简单方法是什么?
- java - 具有自定义提供者 @PreAuthorize 的 Spring Security 返回“访问被拒绝(用户不是匿名的)”但用户具有授权
- puppeteer - Expect 元素包含类名 puppeteer