views:

11

answers:

1

I have this form that allows user to send a message to an email and I want to put validation on it. I do not have a model for this, only controller. How should I do this in rails? Should I do it on the controller?

I also want to flash the errors to the user. If you have a better way of doing this, please let me know. THank you.

+1  A: 

The best approach would be to wrap up your pseudo-model in a class, and add the validations there. The Rails way states you shouldn't put model behavior on the controllers, the only validations there should be the ones that go with the request itself (authentication, authorization, etc.)

In Rails 2.3+, you can include ActiveRecord::Validations, with the little drawback that you have to define some methods the ActiveRecord layer expects. See this post for a deeper explanation. Code below adapted from that post:

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 sexy validations at your disposal :)

Chubas
sweetness!!!!!!!
denniss