Where should Rails 3 custom validators be stored?

前端 未结 4 1532
无人共我
无人共我 2020-12-04 17:00

I\'ve seen docs/websites show that custom validators should go in a /lib or /lib/validators directory of a project. I\'ve found (by reading an answ

相关标签:
4条回答
  • 2020-12-04 17:43

    lib/validators seems by far the cleanest. However you may need to load them in before your models, so probably from an initializer.

    0 讨论(0)
  • 2020-12-04 17:50

    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.

    0 讨论(0)
  • 2020-12-04 17:50

    Here's the official docs about custom validations. AFAIK its a good practice to keep them in the relevant models.

    0 讨论(0)
  • 2020-12-04 17:53

    If you place your custom validators in app/validators they will be automatically loaded without needing to alter your config/application.rb file.

    0 讨论(0)
提交回复
热议问题