如何对关联错误消息进行分组



我有一个User模型,它是has_one :address, as: :addressable。这里的地址是多态关联。

保存用户时,如果出错。由于验证失败,错误未按地址分组

user.errors.to_json的输出为

"{"address.city":["can't be blank"],"address.state":["can't be blank"],"address.country":["can't be blank"],"address.zipcode":["can't be blank","is invalid"],"address.business_phone":["is invalid"],"name":["can't be blank"]}"

我希望输出是

"address: {city: ["can't be blank], state: ["can't be blank]..}"

是否可以将错误消息分组或排除关联的错误消息?

因为user.address.errors似乎提供了我所需要的,但我需要在没有地址模型错误的情况下获得用户模型错误。

工作解决方案

# Note: This modifies the given Hash
def extract_address_errors_from_user_errors!(user_errors_hash)
address_error_prefix = 'address.'
empty_str = ''
address_error_keys = []
address = Address.new
user_errors_hash.each do |k, v|
unless k.start_with?(address_error_prefix)
next
end
# Collect the address error keys to later remove them from user errors hash
address_error_keys << k
address_attr_name = k.gsub(address_error_prefix, empty_str)
address_attr_name_sym = address_attr_name.to_sym
address.errors.add(address_attr_name_sym, v)
address.errors[address_attr_name_sym].flatten!
end

# Remove the address errors from user errors
user_errors_hash.except!(*address_error_keys)
address.errors.to_hash
end

用法

user_errors_hash = user.errors.to_hash
address_errors_hash = extract_address_errors_from_user_errors!(user_errors_hash)
user_errors_hash.merge!(address: address_errors_hash)
# This should give you the desired output
user_errors_hash.to_json

最新更新