forget about the view

Recently I was looking at some of ActiveRecord‘s class level validation methods and realizing I don’t really use a lot of them. Until I took a look at #validates_inclusion_of.

Say we got

class Event < ActiveRecord::Base

  TYPES = %w(daily weekly monthly)



events (id, title, event_type)



<%= :event_type, Event::TYPES, :include_blank => true %>

So when POST'ing from the form on app/views/events/new.rhtml there’s no chance I’ll get an event type other than the 3 (or blank) I show in the drop down list.

What if someone did a POST via curl and did


'asdf’ is not one of my Event::TYPES but my Event record is still going to save. I know this is probably far fetched but we should be building our models without any notion of the UI, be it browser or not. So we need validations for everything.

Here’s what we should be doing

class Event < ActiveRecord::Base

  TYPES = %w(daily weekly monthly)

  validates_inclusion_of :event_type,
    :in => TYPES