我见过文档/网站显示,自定义验证器应该放在项目的 /lib或 /lib/validators目录中。我发现(通过阅读对另一篇文章的回答)它们似乎只在 config/initializers中起作用。是否有人知道,或有一个指针指向官方文件,显示自定义验证器应该居住在哪里?
/lib
/lib/validators
config/initializers
Here's the official docs about custom validations. AFAIK its a good practice to keep them in the relevant models.
lib/validators seems by far the cleanest. However you may need to load them in before your models, so probably from an initializer.
lib/validators
If you add this to your /config/application.rb file:
config.autoload_paths += %W["#{config.root}/lib/validators/"]
Then Rails will automatically load your validators on start up (just like /config/initializers/), but you keep the clean structure of having your validators in one nice, well named spot.
If you place your custom validators in app/validators they will be automatically loaded without needing to alter your config/application.rb file.
app/validators
config/application.rb