简体   繁体   English

rails自定义验证器 - 添加到模型或控制器中的错误?

[英]rails custom validator - add to errors in model or controller?

I see custom validators being used in models (good) but I also see the validators themselves adding to the record errors object. 我看到模型中使用的自定义验证器(好)但我也看到验证器本身添加到记录错误对象。
eg I see (changed example) 我看到了(改变了例子)

class Title < ActiveRecord::Base
   # implement the method called during validation
   def validate_each(record, attribute, value)
     record.errors[attribute] << 'must be Mr / Mrs / Dr.' unless ['Mr.', 'Mrs.', 'Dr.'].include?(value)
   end
end

This feels a bit like a state thing that should be being done in the controller and the validation should just return true / false but maybe not. 这感觉有点像应该在控制器中完成的状态事情,验证应该只返回true / false但可能不是。

I think this would be a case by case thing. 我认为这将是一个案例的事情。 In general the messaging on validation really doesn't happen in the controller at all. 通常,验证消息确实不会在控制器中发生。 When you use a canned validator you can specify the message differently by manipulating the .yml files and to do so you adjust things and add values under the model, not the controller. 当您使用预制验证器时,您可以通过操作.yml文件来不同地指定消息,并且这样做可以调整内容并在模型下添加值,而不是控制器。

In fact I would suggest always putting the messages that are custom into the locales .yml files 事实上,我建议始终将自定义的消息放入locales .yml文件中

I can see an argument for putting more general failure messages in the controller. 我可以看到在控制器中放置更多一般失败消息的论据。

I tend towards this pattern: 我倾向于这种模式:

errors.add[:name] << :invalid_honorific

Where the error set by the model is a symbol (acting more like an error code), which is then handled by the view layer, .yml files of whatever. 模型设置的错误是一个符号(更像是一个错误代码),然后由视图层, .yml文件处理。 This avoids putting too much presentation layer stuff in the model. 这避免了在模型中放置过多的表示层内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM