重写属性函数rails mongoid

发布于 2024-10-25 20:49:27 字数 468 浏览 1 评论 0原文

我有一个这样的模型。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰沐子 2024-11-01 20:49:27

如果您想在模型级别强制执行此模式,那么您可以覆盖 setter 和 getter:

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

在这种情况下,您将可以免费编辑/显示,而无需编写任何帮助程序。

尽管如此,我认为正确的方法是在视图级别通过帮助器定义。模型不应该关心这个。

If you want to enforce this pattern at the model level then you could override the setters and getters:

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

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.

无尽的现实 2024-11-01 20:49:27

查看 ActionView::Helpers::NumberHelper。在您的情况下,您可以像这样编写自己的帮助程序:

def money_to_textbox (money)
    money / 100
end

此帮助程序方法应放置在 app\helpers 中,然后在您可以使用的视图中,如下所示:

<%= money_to_textbox @money %>

Look at ActionView::Helpers::NumberHelper. In your case you could write your own helper like this:

def money_to_textbox (money)
    money / 100
end

This helper method should be placed in app\helpers and then in a view you can use like this:

<%= money_to_textbox @money %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文