0

I have a model that looks like this in my schema.rb

create_table "runs", force: true do |t|
    ...
    t.string   "label", default: "Default Run Title", null: false
    ...
    t.datetime "timestamp"
end

However, when I create a new run leaving the label field blank in the form, It stores the run like:

=> #<Run... label: "", .....>

I want to force the default value set to default: "Default Run Title if the string is passed as an empty string.

What am I missing?

I suppose I can use a validator method or a before_save or something, but I'd rather have the model govern this behavior since this is well within the realm of what default => is supposed to do I thought...

Alex Neigher
  • 887
  • 1
  • 10
  • 22

1 Answers1

3

Putting junk like that in your database schema is really, really annoying. What if later you need to change that phrasing? Then you need to run a migration. What if you want the phrasing to change based on the user's language? Then you need to write a hack to work around it.

What's better is to put this in your model:

before_validation :assign_default_label

Then later have a method that defaults it:

def assign_default_label
  return if (self.label?)

  self.label = "Default Run Title"
end

Any time you need to change that phrasing you can just re-deploy without having to alter the schema.

The label? method in a model will return true if there's a title assigned that contains something other than spaces. This means blank titles are replaced with whatever phrasing you want. These methods are automatically generated by ActiveRecord.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Thanks @tadman. Will title? work for label? Or will i have to write a custom label? method that does the same thing – Alex Neigher Dec 05 '14 at 20:04
  • 2
    Oh, right, I'll change the name there, got tripped up on your phrasing of "Default Run Title" not "Label". This principle will work on any string column. – tadman Dec 05 '14 at 20:05