I was just wondering what the recommended approach would be for validating a form that is not based on a model. I agree that generally all validation should be done in models but there are situations where a particular form might not have a corresponding model(s). For example, an arbitrary search form.
Based on my current research, there are two main ways of doing it as far as I can see,
SearchForm
and include the ActiveRecord::Validations
Absolutely #2. ActiveModel::Validations API is what you're looking for
class ArbitrarySearch
include ActiveModel::Validations
attr_accessor :query
validate :query, :presence
end
As for where this should go, yes, it should go in app/models
. If you're like me and think the mix of models extending ActiveRecord::Base
and those that don't coexisting within the same directory smells funny, consider adding the following to your config/application.rb
file
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
Now, you can organize your model files in whatever way you like. For me I have
- app
|
|- models
|
|- table
|- tableless
|- observer
and I drop classes like your ArbitrarySearch
class into app/models/tableless/arbitrary_search.rb
.
There is a great gem to get this and other common functionality you use within ActiveRecord models into generic non-table-based model classes called active_attr.
ActiveAttr is a set of modules that makes it easy to create plain old ruby models with functionality found in ORMs, like ActiveRecord, without reinventing the wheel. Think of ActiveAttr as the stuff ActiveModel left out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With