代码之家  ›  专栏  ›  技术社区  ›  Jeff Locke

如何通过单表继承访问父属性?

  •  1
  • Jeff Locke  · 技术社区  · 11 年前

    我在一个项目中使用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
    

    我正试图弄清楚如何让Rectangle的profile方法返回Shape的+它自己的。它应该会导致

    (properties => 21, location => 32)
    

    知道如何从继承的孩子那里访问父母吗?它只是超级的吗?在过去的几天里一直被困在这个问题上。非常感谢您的帮助!

    1 回复  |  直到 11 年前
        1
  •  0
  •   Peter Alfvin    11 年前

    是的,就这么简单。:-)你只是有几个不恰当的文字 {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}