After much trial-and-error and searching for an existing answer, there seems to be a fundamental misunderstanding I'm having and would love some clarification and/or direction.
Note in advance: I'm using multiple table inheritance and have good reasons for doing so, so no need to direct me back to STI :)
I have a base model:
class Animal < ActiveRecord::Base
def initialize(*args)
if self.class == Animal
raise "Animal cannot be instantiated directly"
end
super
end
end
And a sub-class:
class Bunny < Animal
has_one(:bunny_attr)
def initialize(*args)
attrs = args[0].extract!(:ear_length, :hop_style)
super
self.bunny_attr = BunnyAttr.create!
bunny_attrs_accessors
attrs.each do |key, value|
self.send("#{key}=", value)
end
def bunny_attrs_accessors
attrs = [:ear_length, :hop_style]
attrs.each do |att|
define_singleton_method att do
bunny_attr.send(att)
end
define_singleton_method "#{att}=" do |val|
bunny_attr.send("#{att}=", val)
bunny_attr.save!
end
end
end
end
And a related set of data
class BunnyAttr < ActiveRecord::Base
belongs_to :bunny
end
If I then do something like this:
bunny = Bunny.create!(name: "Foofoo", color: white, ear_length: 10, hop_style: "normal")
bunny.ear_length
Bunny.first.ear_length
bunny.ear_length will return "10", while Bunny.first.ear_length will return "undefined method 'ear_length' for #<Bunny:0x0..>
Why is that and how do I get the second call to return a value?