嵌套模型错误消息 [英] Nested model error messages
问题描述
我正在使用Ruby on Rails 3.0.9,并且正在尝试验证嵌套模型.假设我对主要"模型进行了验证,并且为嵌套模型生成了一些错误,则得到以下信息:
I am using Ruby on Rails 3.0.9 and I am trying to validate a nested model. Supposing that I run validation for the "main" model and that generates some errors for the nested model I get the following:
@user.valid?
@user.errors.inspect
# => {:"account.firstname"=>["is too short", "can not be blank"], :"account.lastname"=>["is too short", "can not be blank"], :account=>["is invalid"]}
如何看到RoR框架创建具有以下键的errors
哈希:account.firstname
,account.lastname
,account
.由于我想通过使用涉及CSS属性的JavaScript(BTW:我使用jQuery)处理这些错误键/值对来在前端内容上显示错误消息,因此我认为可以准备"该数据并将这些键更改为account_firstname
,account_lastname
,account
(注意:我将.
替换为_
字符).
How you can see the RoR framework creates an errors
hash having following keys: account.firstname
, account.lastname
, account
. Since I would like to display error messages on the front-end content by handling those error key\value pairs with JavaScript (BTW: I use jQuery) that involves CSS properties I thought to "prepare" that data and to change those keys to account_firstname
, account_lastname
, account
(note: I substitute the .
with the _
character).
如何将键值从例如account.firstname
更改为account_firstname
?
How can I change key values from, for example, account.firstname
to account_firstname
?
而且,最重要的,我应该如何处理这种情况?我正在尝试做一个好的"方式来处理嵌套模型错误吗?如果不是,那么最常见的\最佳方法是什么?
And, mostly important, how I should handle this situation? Is what I am trying to do a "good" way to handle nested model errors? If no, what is the common\best approach to do that?
推荐答案
Rails错误哈希的一些创造性修补可以使您实现目标.在config/initalizers
中创建一个初始化程序,将其命名为errors_hash_patch.rb
并将以下内容放入其中:
Some creative patching of the Rails errors hash will let you achieve your aim. Create an initializer in config/initalizers
, let call it errors_hash_patch.rb
and put the following in it:
ActiveModel::Errors.class_eval do
def [](attribute)
attribute = attribute.to_sym
dotted_attribute = attribute.to_s.gsub("_", ".").to_sym
attribute_result = get(attribute)
dotted_attribute_result = get(dotted_attribute)
if attribute_result
attribute_result
elsif dotted_attribute_result
dotted_attribute_result
else
set(attribute, [])
end
end
end
您在这里所做的只是简单地重写访问器方法[]
,以使其更加努力.更具体地说,如果您要查找的键具有下划线,它将尝试按原样查找它,但是如果找不到任何内容,它还将所有下划线都替换为点并尝试对其进行查找.除此之外,该行为与常规[]
方法相同.例如,假设您有一个错误哈希,例如您的示例中的错误:
All you're doing in here is simply overriding the accessor method []
to try a little harder. More specifically, if the key you're looking for has underscores, it will try to look it up as is, but if it can't find anything it will also replace all the underscores with dots and try to look that up as well. Other than that the behaviour is the same as the regular []
method. For example, let's say you have an errors hash like the one from your example:
errors = {:"account.firstname"=>["is too short", "can not be blank"], :"account.lastname"=>["is too short", "can not be blank"], :account=>["is invalid"]}
以下是您访问它的一些方法以及返回的结果:
Here are some of the ways you can access it and the results that come back:
errors[:account] => ["is invalid"]
errors[:"account.lastname"] => ["is too short", "can not be blank"]
errors[:account_lastname] => ["is too short", "can not be blank"]
errors[:blah] => []
我们不会更改密钥在错误哈希中的存储方式,因此我们不会意外破坏可能依赖于哈希格式的库和行为.关于如何访问哈希中的数据,我们正在做的是变得更加聪明.当然,如果您确实想更改哈希中的数据,则模式是相同的,您只需要覆盖[]=
方法,并且每次Rails尝试在其中存储带点的键时,只需将点更改为下划线.
We don't change the way the keys are stored in the errors hash, so we won't accidentally break libraries and behaviours that may rely on the format of the the hash. All we're doing is being a little smarter regarding how we access the data in the hash. Of course, if you DO want to change the data in the hash, the pattern is the same you will just need to override the []=
method, and every time rails tries to store keys with dots in them, just change the dots to underscores.
关于您的第二个问题,即使我已向您展示了如何处理您要问的问题,总的来说,最好还是遵循导轨尝试做事的方式,而不是尝试将导轨弯曲到您的身上将要.在您的情况下,如果要通过javascript显示错误消息,大概是您的javascript将可以访问错误数据的哈希,所以为什么不使用javascript将此数据调整为所需的格式.或者,您可以在控制器内部克隆错误数据并对其进行调整(在您的JavaScript曾经访问过它之前).很难在不了解您的情况的情况下提供建议(您如何编写表单,验证JS到底想做什么等),但这是一些通用准则.
As to your second question, even though I have shown you how to do what you're asking, in general it is best to try and comply with the way rails tries to do things, rather than trying to bend rails to your will. In your case, if you want to display the error messages via javascript, presumably your javascript will have access to a hash of error data, so why not tweak this data with javascript to be in the format that you need it to be. Alternatively you may clone the error data inside a controller and tweak it there (before your javascript ever has access to it). It is difficult to give advice without knowing more about your situation (how are you writing your forms, what exactly is your validation JS trying to do etc.), but those are some general guidelines.
这篇关于嵌套模型错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!