Jared Carroll

Here’s one that might get you Rails developers:

class Comment < ActiveRecord::Base

  def before_create
    self.spam = false



comments (id, spam)

The above model was in an app that allowed site administrators the ability to flag a Comment as spam. Naturally, this mapped to a boolean column in the comments table.

However, no Comment was ever being saved.


In Rails, if any ActiveRecord callback returns false the model will NOT be saved.

The solution is to put the spam column’s default value of false for all newly created Comment’s in the Comment model’s migration:

class CreateComments < ActiveRecord::Migration

  def self.up
    create_table :comments do |t|
      t.column :spam, :boolean, :default => false

  def self.down
    drop_table :comments


This is one instance were a domain ‘constraint’, if you can call it that, has to go in the database and not in the model.

I love stuff like this.

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.