Rails 3: display validation errors for the form (without saving the ActiveRecord model)

Sorry if this is a really general and / or funny question; I swear I read the documentation several times, and everything seems so focused on ActiveRecord that they wandered along the path of forms that do something other than creating or editing model data.

Take, for example, a form with inputs to control the extraction and display of some statistics. What rails provide me with for checking user input of this form, which will not call savefor any records? Such things as:

  • :email must have an email address
  • :num_products must be a positive integer
  • :gender must be one of "M" or "F"
  • :temperature should be from -10 to 120

Etc etc. (material that is standard on most web frameworks) ...

Is there anything in Rails to do this arbitrary check and some kind of view helper to display a list of errors, or is everything related to ActiveRecord?

Sorry if I missed this in the documentation, but this and this does not really cover it, at least as far as tired eyes can get.

head scratches

Thanks Rob, that’s what I came up with. I created a utility class (aptly named Validator) that is simply built into my controllers for everything 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

, .rb, IMHO. , , Ruby Rails.

+5
2

, .

API validations.

, , , 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
+6

, .

model.save, model.valid?

0

All Articles