2013-08-22 29 views
0

我試圖實現這種模式Mongoid覆蓋關係二傳手

class A 
    Mongoid::Document 

    belongs_to :price 

    def price 
     self[:price] || calculate_price 
    end 

    def calculate_price 
     #Some logic 
    end  
end 

這意味着用戶可以促使物價A或得到一個計算價格。麻煩的是,二傳手無法按預期工作:

2.0.0-rc2 :013 > a = A.new 
=> #<A _id: 5215b3321d41c89a1f000001, price_id: nil> 
2.0.0-rc2 :015 > a.price = Price.new 
=> #<Price _id: 5215b3451d41c89a1f000002, i(inclusive_tax): nil, e(exclusive_tax): nil, tax_id: nil> 
2.0.0-rc2 :016 > a.price 
=> "5215b3451d41c89a1f000002" 

什麼是重寫setter的方法,所以事情按預期工作?

我嘗試添加

def price=(val) 
    super(val) 
end 

但沒有super的制定者。

任何提示?

回答

0

這個解決方法如何?

class A 
    Mongoid::Document 

    belongs_to :price 

    def price 
     Price.find(self[:price]) || calculate_price 
    end 

    def calculate_price 
     #Some logic 
    end  
end 
+0

就性能而言,它應該與自身[:價格]僅適用於相同,因爲它們仍然會遍歷所有價格記錄中的_id字段。 –

+0

問題出在自我[:價格]調用不起作用(儘管它與PostGreSQL有關)。重點是要知道要訪問關係的屬性。 – muichkine

+0

是read_attribute(:price)working? –