1

I want to add a virtual attribute to an activerecord object. It's straightforward to define the getter/setter but I want my attribute to appear in the attributes hash (and attribute_names etc..). Since this is rails 4 I can't use attr_accessible.

What more do I need to add to this code so I can call reference.attributes and have the value of authors show up there?

class Reference < ActiveRecord::Base

  def authors
    self.author_names.to_a.join(' and ')
  end

  def authors=(val)
    self.author_names.destroy
    val.strip.split(/(?:[ ]and[ ])|\;/).each {|entry|
     self.author_names << AuthorName.new(name: entry)
    }
  end
end
Peter Gerdes
  • 2,288
  • 1
  • 20
  • 28

1 Answers1

5
def attributes
  super.merge({'authors' => authors})
end
Austio
  • 5,939
  • 20
  • 34