I have a form that allows the user to send a message to an email, and I want to add validation to it. I do not have a model for this, only a controller. How should I do this
For Rails 3+, you should use ActiveModel::Validations to add Rails-style validations to a regular Ruby object.
From the docs:
Active Model Validations
Provides a full validation framework to your objects.
A minimal implementation could be:
class Person include ActiveModel::Validations attr_accessor :first_name, :last_name validates_each :first_name, :last_name do |record, attr, value| record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z end endWhich provides you with the full standard validation stack that you know from Active Record:
person = Person.new person.valid? # => true person.invalid? # => false person.first_name = 'zoolander' person.valid? # => false person.invalid? # => true person.errors.messages # => {first_name:["starts with z."]}Note that
ActiveModel::Validationsautomatically adds an errors method to your instances initialized with a newActiveModel::Errorsobject, so there is no need for you to do this manually.