Validation in Rails without a Model

I have a form that allows the user to send an email, and I want to add a confirmation to it. I do not have a model for this, only for the controller. How to do it in Rails?

I considered the possibility of validation in the controller and displaying errors to the user using the flash object. Is there a better way to do this?

+7
ruby-on-rails
source share
2 answers

A better approach would be to wrap your pseudo-module in a class and add validations there. In Rails mode, it is indicated that you should not put model behavior on controllers, the only checks should be those that go with the request itself (authentication, authorization, etc.).

In Rails 2.3+, you can enable ActiveRecord::Validations , with the slight drawback that you must define some methods that the ActiveRecord layer expects. See this post for a deeper explanation. Below is the code below:

 require 'active_record/validations' class Email attr_accessor :name, :email attr_accessor :errors def initialize(*args) # Create an Errors object, which is required by validations and to use some view methods. @errors = ActiveRecord::Errors.new(self) end # Required method stubs def save end def save! end def new_record? false end def update_attribute end # Mix in that validation goodness! include ActiveRecord::Validations # Validations! =) validates_presence_of :name validates_format_of :email, :with => SOME_EMAIL_REGEXP end 

In Rails3, you have those sexual checks at your disposal :)

+6
source share

For Rails 3+, you must use ActiveModel::Validations to add validation checks to the regular Ruby object.

From the docs :

Validating an Active Model

Provides a complete validation structure for your objects.

The minimum implementation may 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 end 

which provides you with the full standard validation stack that you learn from the 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::Validations automatically adds an error method for your instances initialized with the new ActiveModel::Errors object, so you do not need to do this manually.

+2
source share

All Articles