ActiveRecord database :default “gotcha”

In: Ruby on Rails

19 Sep 2007

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 are closed.