我使用STI(正确的,我保证!)为对象的一个关系:Rails的STI建立关系
class Walrus < ActiveRecord::Base
has_one :bubbles
end
class Bubbles < ActiveRecord::Base
belongs_to :walrus
before_save :set_origin
private
def set_origin
self.type = walrus.state ? "Bubbles::#{walrus.state}" : 'Bubbles'
end
end
class Bubbles::OfMind < Bubbles
def tango
end
end
现在,如果我建立一个新的关系,类设置不正确:
harold = Walrus.new(state: 'OfMind')
harold.build_bubbles.save!
harold.bubbles
# => returns instance of Bubbles, not Bubbles::OfMind
harold.bubbles.tango
# NoMethodError
Bubbles对象不能神奇地成为Bubbles :: OfMind,但直到关系是正确的类型,正确的功能不存在。
你可能需要拼出来,因为我在这里看不到一丝性病。我看到三个没有继承的裸类。 Walrus是否应该是超类? – Substantial
添加了继承 – Chris
什么是build_bubbles方法? –