2013-10-17 68 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'在這種情況下返回父項的散列。至於你的第一個問題,我會說「是」,如果你想保存結果並訪問它,而無需再次調用父方法。 –