---
title: what
teaser:
tags: web,rails
author: Jared Carroll
published_on: 2007-07-12
---

Here's one that might get you Rails developers:

```ruby
class Comment < ActiveRecord::Base

  def before_create
    self.spam = false
  end

end
```

Schema:

    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.

Why?

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:

```ruby
class CreateComments < ActiveRecord::Migration

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

  def self.down
    drop_table :comments
  end

end
```

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.
