如何在活动模型中以零金额初始化 Money 列?
我有一个新的应用程序(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
after_initialize 并没有像你想象的那样做,它
也挂钩到 init 中,如下所示:
after_initialize does not do what you think it does
the way too hook into init is as follows: