Welcome to Giant Robots Smashing Into Other Giant Robots — a weblog about development, business, design and technology — written by thoughtbot.
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
1 2 3 4 5 |
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&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
1 2 3 4 5 6 7 8 |
class Event < ActiveRecord::Base TYPES = %w(daily weekly monthly) validates_inclusion_of :event_type, :in => TYPES end |
About this entry
You're reading an entry on GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS, the company weblog of thoughtbot, inc.
- Author:
- Jared Carroll
- Published:
- September 24th 08:37 AM
- Updated:
- September 30th 09:57 AM
- Sections:
- Development
thoughtbot is hiring
We are hiring web developers and web designers in both Boston and New York, NY.
What are we up to?
We built Shoulda, an eclectic set of additions to Test::Unit; Paperclip to manage uploaded files without hassle; Jester, a REST/ActiveResource client library written in Javascript, and Squirrel, an enhancement for ActiveRecord's find syntax; — amongst some other projects.

Chad (President) and Jon (CTO) co-authored a technical book titled Pro Active Record: Databases with Ruby and Rails, which explores the ins and outs of the ActiveRecord ruby library. You can buy it today at Amazon.com.
About thoughtbot, inc.
We are a small web application development consulting business, with offices in Boston, MA and New York, NY. If you're looking to find a team for your next web development project or your new web application — get in touch.
8 comments
Jump to comment form