Wednesday, March 2, 2011

Default Values in ActiveRecord Fields

Looking at some of the incident report controller code, I noticed a few rogue constants floating around. They appeared to be primary key values of default values for, e.g. infractions.

Let me propose an alternative: set the default in the ActiveRecord code. There are a variety of approaches discussed here.

Check it out.

So, we should consider something like:
class RecordedInfraction < ActiveRecord::Base
  after_initialize :default_values

  private
    def default_values
      self.infraction_id ||= Infraction.find_by_name("FYI").id
    end
end

That way we can reduce the WTFs when reading our code.