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

2
  • 1
    the problem is the "" != Null. take a look at stackoverflow.com/questions/7202319/… Commented Dec 5, 2014 at 19:47
  • Please show your params to the create method. Commented Dec 5, 2014 at 19:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @tadman. Will title? work for label? Or will i have to write a custom label? method that does the same thing
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.