多くの試行錯誤と既存の回答の検索の後、私が抱えている根本的な誤解があるようで、明確化および/または方向性が大好きです。
事前に注意してください:私は複数のテーブル継承を使用しており、そうするのには十分な理由があるので、STIに戻す必要はありません:)
私は基本モデルを持っています:
class Animal < ActiveRecord::Base
def initialize(*args)
if self.class == Animal
raise "Animal cannot be instantiated directly"
end
super
end
end
そしてサブクラス:
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
関連する一連のデータ
class BunnyAttr < ActiveRecord::Base
belongs_to :bunny
end
次に、次のようなことをすると:
bunny = Bunny.create!(name: "Foofoo", color: white, ear_length: 10, hop_style: "normal")
bunny.ear_length
Bunny.first.ear_length
bunny.ear_length は「10」を返し、Bunny.first.ear_length は「#<Bunny:0x0..> に対して未定義のメソッド 'ear_length'」を返します。
それはなぜですか?また、2 番目の呼び出しで値を返すにはどうすればよいですか?