经过多次尝试和错误,并寻找一个现有的答案,似乎有一个根本性的误解,我有,并希望得到一些澄清和/或方向。
注意:我正在使用多个表继承,并且有很好的理由这样做,所以不需要指示我回到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_lengthbunny.ear_length将返回"10",而Bunny.first.ear_length将返回#的“未定义方法'ear_length‘。
为什么是这样,以及如何获得第二个调用来返回值?
发布于 2014-07-02 00:47:36
Sean在回答中描述的代表团工作得很好,但是我想要一些更通用的东西,因为我将拥有相当多的“动物”,并且不想每次我向BunnyAttr添加一个新的列时都要更新委托行,并且我试图将尽可能多的代码移到动物类上。
然后我偶然发现了这篇博文,并决定在Bunny类中使用method_missing (最终将在动物类中定义一个版本,我将在其中传递attr类)。
def method_missing(method_name, *args, &block)
bunny_attr.respond_to?(method_name) ?
bunny_attr.send(method_name, *args) :
super
end当然会喜欢评论为什么这是一个坏主意,如果有的话。
https://stackoverflow.com/questions/24500809
复制相似问题