如何在活动模型中以零金额初始化 Money 列?

发布于 2024-09-18 12:49:14 字数 461 浏览 3 评论 0原文

我有一个新的应用程序(Rails 2.3.8),它使用大量的货币字段。我正在使用 Money gem (3.0.5) 和acts_as_money 插件。我已经编写了许多 rspec 模型示例,并且一切似乎都工作正常。

我的问题是定义 new & 的表单。编辑。正如我在过去的复杂布局项目中所做的那样,我将基本形式提取到部分并将其包含在新的 & 中。编辑视图。

然而,模型对象被创建并在字段中留下空值,并导致钱宝石抱怨:“undefined method `subunit_to_unit' for nil:NilClass”。

我想我可以使用像 after_initialize() 这样的东西来挂钩在 Rails 中创建一个新对象并将所有的钱属性设置为零,但这不起作用(并且有几篇文章建议反对该方法)出于性能原因)...

关于一种干净的方法来挂钩我的模型对象并确保它的所有货币值都为零有什么建议吗?

I have a new app (Rails 2.3.8) that uses lots of money fields. I'm using the money gem (3.0.5) and the acts_as_money plugin. I've written a number of rspec model examples and everything seems to be working fine there.

My problem is in defining forms for new & edit. As I've done in past projects for complex layouts, I extracted the basic form to a partial and include it in the new & edit views.

However, the model object is created and left with nulls in the fields, and causes the money gem to complain with: "undefined method `subunit_to_unit' for nil:NilClass".

I thought I could use something like after_initialize() to hook into the creation of a new object in Rails and set all the money attributes to zero, but that didn't work (and several posts recommended against that for performance reasons)...

Any suggestions on a clean way to hook my model object and make sure it's got zeros for all the money values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

断桥再见 2024-09-25 12:49:14

after_initialize 并没有像你想象的那样做,它

也挂钩到 init 中,如下所示:

class MyModel < ActiveRecord::Base

  def initialize(*args, &block)
     super         # no () form is equivalent to super(*args, &block)
     set_defaults
  end

  private

  def set_defaults
    # Do your defaults here
  end

end

after_initialize does not do what you think it does

the way too hook into init is as follows:

class MyModel < ActiveRecord::Base

  def initialize(*args, &block)
     super         # no () form is equivalent to super(*args, &block)
     set_defaults
  end

  private

  def set_defaults
    # Do your defaults here
  end

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