ActiveRecord database :default “gotcha”

Note to self:

When a table column has a default value, such as for the type_category column/attribute like so:

t.string :type_category, :limit => 20, :nil => false, :default => 'tv'

a new instance of your ActiveRecord model will try and set the defaults from the database. Meaning:

Anime.new => #<Anime id: nil, type_category: "tv"...

Courtesy of this in ActiveRecord::Base:

def attributes_from_column_definition
  self.class.columns.inject({}) do |attributes, column|
    attributes[column.name] = column.default unless column.name == self.class.primary_key
    attributes
  end
end

So, don’t get confused when your model validations (validates_presence_of :type_category) don’t seem to work when testing:

it "should require a type_category" do
  @foo.attributes = valid_foo_attributes.except(:type_category)
  @foo.should have(1).error_on(:type_category)  # doesn't work since @foo.type_category = 'tv'
end

Explicitly set it to nil or a blank value.

Sounds silly, but it’s a true story.

Comments & TrackBacks (Add yours)

The paper doll icon that precedes each comment is an idea conceived by Vanessa Tan.

There are no comments yet. Somebody say something!

You can subscribe to the RSS feed for comments on this post.

Post a comment

(required)

(required, but never displayed)


You can format your comments using XHTML. Your email address will not be displayed or used for nefarious purposes.

Only following tags are allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>