Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation of non-models

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,

  1. 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.

  2. Create an arbitrary class eg. called SearchForm and include the ActiveRecord::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!

  3. Any other suggestions?
like image 560
richard Avatar asked Dec 09 '12 03:12

richard


Video Answer


1 Answers

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.

like image 75
deefour Avatar answered Sep 24 '22 16:09

deefour