MongoMapper——通过表单更新浮动:如何映射“” =>零(而不是 0.0)?
我有一个rails3项目,使用mongodb + MongoMapper。我有一个带有浮点值的模型,用户可以通过表单进行设置。提交表单时,如果没有为 foo_val 指定任何值,则参数将作为空字符串传递,最终将属性值设置为 0.0,这不是我想要的。我想区分用户提交的值“0”和用户提交的“空”值(“”),即清除属性。
我怎样才能做到这一点?
class Foo
include MongoMapper::Document
key :foo_val, Float
end
I have a rails3 project, using mongodb + MongoMapper. I have a model with a float value, which the user can set via a form. When the form is submitted, if no value is given for foo_val, the param is passed as the empty string, which winds up setting the attribute value to 0.0, which is not what I want. I want to differentiate between a user submitted value of "0", and user submitted "null" value (""), i.e. clearing the attribute.
How can I accomplish this?
class Foo
include MongoMapper::Document
key :foo_val, Float
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的答案有效 - 你可以将其移至文档的 before_save 操作。您可以尝试的另一件事是 validates_numericality_of :foo_val, :allow_nil => true
这可能会起作用,据说它将空字符串转换为 nil。
I think your answer works - you could move it to the before_save action of the Document. Another thing you could try is validates_numericality_of :foo_val, :allow_nil => true
That might work, supposedly it casts empty strings to nil.
好吧,这就是我的想法。可能有更好的方法来做到这一点:
我在 Foo 控制器中添加了一个 before 过滤器,以挂钩一个在创建、更新、编辑和保存之前检查浮动参数的函数,如下所示:
Ok, here is what I've figured out. There might well be a better way to do this:
I added a before filter in the Foo controller, to hook a function that checks my float params before create, update, edit, and save like so: