forget about the view

Jared Carroll

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)

end

schema

events (id, title, event_type)

view

app/views/events/new.rhtml

<%= form.select :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

event[title]=title&amp;event[event_type]=asdf

‘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

end
Jared Carroll

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.