2013-10-17 59 views
1

我正在使用STI的项目,我希望每个模型都有一个返回散列的方法。该散列是该模型的特定配置文件。我希望每个孩子模型都能检索父母的散列并将其添加到自己的散列中。下面是一个例子如何通过单个表继承访问父属性?

class Shape 
include Mongoid::Document 
field :x, type: Integer 
field :y, type: Integer 
embedded_in :canvas 

def profile 
    { properties: {21} } 
end 
end 



class Rectangle < Shape 
field :width, type: Float 
field :height, type: Float 

def profile 
    super.merge({ location: {32} }) 
end 
end 

我想弄清楚如何获得矩形的配置文件方法返回形状+自己的。它应该导致

(properties => 21, location => 32) 

任何想法如何从继承的孩子访问父?它只是超级?在过去的几天里一直停留在此。任何帮助非常感谢!

回答

0

是的,就这么简单。 :-)在{21}{32}中,您刚刚得到了一些不正确的文字。

以下工作:

class Shape 

def profile 
    { properties: 21 } 
end 
end 


class Rectangle < Shape 

def profile 
    super.merge({ location: 32 }) 
end 
end 

rect = Rectangle.new 
puts rect.profile # => {:properties => 21, :location => 32} 
+0

唉,愚蠢的错误。谢谢彼得!超级存储在局部变量中是否有意义?在这个例子中,super会返回父母的散列,不是吗? –

+0

是的,'super'在这种情况下返回父项的散列。至于你的第一个问题,我会说“是”,如果你想保存结果并访问它,而无需再次调用父方法。 –