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,
- Validate in the controller.
- Is it possible to utilise the Rails validations in the controller? I really would prefer to use them over my own custom code.
- Create an arbitrary class eg. called
SearchFormand include theActiveRecord::Validations- Should the class be stored with the models (even though it isn’t really)?
- The posts that recommended this approach indicated you have to stub out a bunch of methods for ActiveRecord such as save, save!, update_attribute, etc. This strikes me as not very Rubyesque at all!
- Any other suggestions?
Absolutely #2. ActiveModel::Validations API is what you’re looking for
As for where this should go, yes, it should go in
app/models. If you’re like me and think the mix of models extendingActiveRecord::Baseand those that don’t coexisting within the same directory smells funny, consider adding the following to yourconfig/application.rbfileNow, you can organize your model files in whatever way you like. For me I have
and I drop classes like your
ArbitrarySearchclass intoapp/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.