重写属性函数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。
也欢迎其他一些解决方案
I have a model like this.
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
total is sum of salary and commission. salary and commission both are saved in cents.
But my problem is that when it is edited i need to show it in dollar figure.
For example, if salary in cent is 5000000 then when i press edit i need to see 50000 in the salary textbox.
Some other solutions are also welcomed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在模型级别强制执行此模式,那么您可以覆盖 setter 和 getter:
在这种情况下,您将可以免费编辑/显示,而无需编写任何帮助程序。
尽管如此,我认为正确的方法是在视图级别通过帮助器定义。模型不应该关心这个。
If you want to enforce this pattern at the model level then you could override the setters and getters:
In this case you'll have the editing/displaying for free, without writing any helpers.
Although, I think the proper way for doing it is at the view level through a helper definition. The model should not be concerned with this.
查看
ActionView::Helpers::NumberHelper
。在您的情况下,您可以像这样编写自己的帮助程序:此帮助程序方法应放置在 app\helpers 中,然后在您可以使用的视图中,如下所示:
Look at
ActionView::Helpers::NumberHelper
. In your case you could write your own helper like this:This helper method should be placed in app\helpers and then in a view you can use like this: