Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Display validation errors for a form (not saving an ActiveRecord model)

Apologies if this is a really common and/or ridiculous question; I swear I've read over the documentation multiple times and everything seems so focused on ActiveRecord to the point they've wandered off the path of forms that do something other than create or edit model data.

Take for example a form with inputs to control the extraction and display of some statistics. What does rails provide me with for validating the user input of this form, which won't be invoking save on any records? Things like:

  • :email must be an email address
  • :num_products must be a positive whole number
  • :gender must be one of "M" or "F"
  • :temperature must be between -10 and 120

Etc etc (the sort of stuff that comes standard in most web frameworks)...

Is there something in Rails for me to perform this arbitrary validation and some view helper to display a list of errors, or is everything coupled with ActiveRecord?

Apologies if I've overlooked this in the documentation, but this and this don't really cover it, at least as far as mt weary eyes can tell.

scratches head

Thanks to Rob's answer, here's what I've come up with. I created a utility class (aptly named Validator) which is just embedded into my controllers for anything that needs it.

module MyApp

    class Validator
        include ActiveModel::Validations
        include ActiveModel::Conversion
        extend  ActiveModel::Naming

        def initialize(attributes = {})
            super
            attributes.each { |n, v| send("#{n}=", v) if respond_to?("#{n}=") }
        end
    end

end

Now in the controller, for example, just define a little inline-class:

class LoginController < ApplicationController
    class AuthenticationValidator < MyApp::Validator
        attr_accessor :email
        attr_accessor :password
        validates_presence_of :email, :message => "E-mail is a required field"
        validates_presence_of :password, :message => "Password cannot be blank"
    end

    def authenticate
        if request.post?
            @validator = AuthenticationValidator.new(params)
            if @validator.valid?
                # Do something meaningful
            end
        end
    end

It feels a bit unnecessary to stick every single set of validation rules in their own .rb when the logic is more controller-oriented IMHO. There is probably a more succinct way to write this, but I'm pretty new to Ruby and Rails.

like image 254
d11wtq Avatar asked May 02 '11 14:05

d11wtq


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How do I bypass validation?

A very common way to skip validation is by keeping the value for immediate attribute as 'true' for the UIComponents. Immediate attribute allow processing of components to move up to the Apply Request Values phase of the lifecycle. scenario: While canceling a specific action, system should not perform the validation.

What is Activerecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What happens on Save rails?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.


1 Answers

Yes, it can be done fairly easily.

You can use the validations API for it.

As an example, here is a contact us model that I use for an application that is not using ActiveRecord.

class ContactUs
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :subject, :message
  validates_presence_of :name, :email, :message, :subject
  validates_format_of :email, :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\z/
  def initialize(attributes=nil)
    attributes.each do |name, value|
      send("#{name}=", value)
    end unless attributes.nil?
  end

  def persisted?
    false
  end
end
like image 169
Rob Di Marco Avatar answered Oct 12 '22 01:10

Rob Di Marco