2012-01-04 102 views
1

沒關係,我有以下型號的軌道:訪問ID

  • 「碎片」
  • 「現實」,這既屬於碎片,或屬於什麼
  • 「空間」,這屬於現實
  • 「屬性」屬於空間

我可以訪問shard.reality.space.first.properties,但我希望能夠通過屬性模型中的自定義方法訪問'shard'id(如果以此方式訪問它)。

有沒有辦法做到這一點?

+0

有人應該指出的是,你在這裏打破了一些嚴重的封裝。德米特法則(http://en.wikipedia.org/wiki/Law_of_Demeter)被普遍解釋爲只有一個點(儘管這是一種過於簡單化),但是你試圖做的事肯定會違反它。該財產只應瞭解自己及其成員;空間是一個「成員」,碎片不是。我會看看你是如何構建的,看看你是否能找到更好的方法。 – karmajunkie 2012-01-04 20:24:05

回答

0
class Property < ActiveRecord::Base 
    belongs_to :space 

    def custom_method 
    space.reality.shard.id if space.reality.shard 
    end 
end 
0

在一個Property對象上的實例方法,這應該工作:

shard_id = space.reality.shard_id 
# returns either the shard id, or nil if the reality doesn't belong to a shard