2011-03-23 58 views
2

我有這樣的模型。覆蓋屬性函數rails mongoid

class Money 
    include Mongoid::Document 

    #interval is how often the compensation is paid 
    field :salary, :type => Integer # must be saved in cents 
    field :commission, :type => Integer # must be saved in cents 
    field :total, :type => Integer # must be saved in cents 
end 

總計是工資和佣金的總和。薪水和佣金都以美分保存。 但我的問題是,當它被編輯時,我需要以美元數字顯示它。

例如,如果薪水分爲5000000,那麼當我按編輯我需要在工資文本框中看到50000。

一些其他的解決方案也受到了歡迎

感謝

回答

2

ActionView::Helpers::NumberHelper。你的情況,你可以編寫自己的助手這樣的:

def money_to_textbox (money) 
    money/100 
end 

這個輔助方法應該放在應用程序\助手,然後在視圖中,可以使用這樣的:

<%= money_to_textbox @money %> 
3

如果你想強制在模型級別這種模式,那麼你可以覆蓋getter和setter方法:

class Money 
    #... 
    def salary 
    self.salary/100 
    end 
    def salary=(value) 
    self.salary * 100 
    end 
end 

在這種情況下,你必須編輯/顯示爲免費,而無需編寫任何助手。

雖然,我認爲這樣做的正確方法是通過助手定義在視圖級別。該模型不應該關心這一點。