Read more

Pitfall: has_defaults on virtual attributes are nil when loaded from database, of course …

Martin Straub
September 04, 2015Software engineer at makandra GmbH

It smells. Rethink your code design.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Code example with makandra/has_defaults Show archive.org snapshot :

class Post < ActiveRecord::Base

  has_defaults tags: []          # field in db
  has_defaults virtual_tags: []  # no db field
  
  def all_tags
    virtual_tags + tags
  end
  
end

> Post.new.virtual_tags
=> []   # ✔

> Post.find(1).virtual_tags
=> nil   # ☹

> Post.find(1).all_tags
=> Error: undefined method '+' for nil:NilClass
Posted by Martin Straub to makandra dev (2015-09-04 17:37)