Rails 金钱宝石和表单生成器
我的表单和 money gem 存在问题。
这是我的问题:
- 我创建一个具有“金额”字段(映射到货币对象)的记录。假设我输入 10(美元)。
- 货币宝石将其转换为 1000(美分)
- 我编辑相同的记录,表单将金额字段预填充为 1000
- 如果我保存记录而不更改任何内容,它将把 1000(美元)转换为 100000(美分)
如何做我让它以美元而不是美分显示预先填充的金额?
编辑:
我尝试像这样编辑 _form.html:
= f.text_field(:amount, :to_money)
并且收到此错误:
undefined method `merge' for :to_money:Symbol
I'm having an issue with the forms and the money gem.
This is my problem:
- I create a record which has an "amount" field (mapped to money object). Let's say I enter 10 (dollars).
- The money gem converts it to 1000 (cents)
- I edit the same record and the form pre-populates the amount field as 1000
- If I save the record without changing anything, it will convert the 1000 (dollars) to 100000 (cents)
How do I make it display the pre-populated amount in dollars instead of cents?
Edit:
I tried editing the _form.html like this:
= f.text_field(:amount, :to_money)
and I get this error:
undefined method `merge' for :to_money:Symbol
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设迁移如下:
模型如下:
那么这个表单代码应该可以完美工作(我刚刚在 Rails 3.0.3 下测试),每次保存/编辑时都能正确显示和保存美元金额。 (这是使用默认的脚手架更新/创建方法)。
Given a migration as follows:
And a model as follows:
Then this form code should work perfectly (I just tested under Rails 3.0.3), properly displaying and saving the dollar amount every time you save/edit. (This is using the default scaffold update/create methods).
您现在可以直接编辑货币化字段 (money-rails 1.3.0):
请参阅 https://stackoverflow.com/a/30763084/46039
You can now edit monetized fields directly (money-rails 1.3.0):
See https://stackoverflow.com/a/30763084/46039
如果表中有多个货币字段,并且不能将它们全部命名为“cents”。
这会将你的模型更改为
If you have multiple money fields in your table and you can't name them all "cents".
which would change your model to
货币化和简单形式,步骤如下:
add_monetize :table, :amount
monetize :amount_cents, allowed_nil: true, numericity: {greater_than: 0}
params.require(: model).permit(:amount)
保存时将以分形式保存在数据库中的 amount_cents 列中
monetizing and the simple form, the steps as follows:
add_monetize :table, :amount
monetize :amount_cents, allow_nil: true, numericality: {greater_than: 0}
params.require(:model).permit(:amount)
when it's saved it will be saved in cents in amount_cents column in db