如何从模型属性中删除空格?
确保模型修剪字符串值中的前导和尾随空格的最简单方法是什么。
一种不方便的方法似乎是 before_save 过滤器——尽管对于像从字符串中删除空格这样常见的事情,也许有一些配置可以做到这一点?
What's the simplest way to make sure models trim leading and trailing white space from string values.
One inconvenient way seems to be a before_save filter -- although for something as common as removing white space from strings, maybe there's some config that does that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有内置的全局/配置设置,因为您不想总是这样做,所以最好根据您所描述的具体情况并使用
strip(field)
在前置过滤器中。尽管雅各布详细说明了这一点,但还是有一颗可用的宝石。我还建议在对用户值进行任何操作时要小心。常见的最佳实践是保存用户输入的“任何内容”,“所有内容”(好吧,在本例中是空格)。然后根据需要进行内部操作和格式显示。
这里的主要推理是,当用户重新编辑他们的信息时,最好为他们提供“他们之前输入的内容”,而不是陷入最终复杂的验证和非常脆弱的用户界面中。
另一个旁注,请确保使用“数据适当”字段,例如不要将日期存储在字符串中,这会带来麻烦。
There isn't a built-in global/config setting for the reason that you would not want to always do this, so it's better done on a case by case basis as you describe and with
strip(field)
in a before filter. There is a gem available though as detailed by Jacob.I also advise caution when doing any manipulation to user values. A common best practice is to save "whatever" the user types, "warts and all" (well ok, spaces in this case). Then manipulate internally and format for display as required.
The main line of reasoning here being that when a user re-edits their info, it's better to give them 'exactly what they typed before' rather than getting caught up in what can end up being complicated validations and very brittle user interfaces.
Another sidenote, make sure to use 'data appropriate' fields, e.g. don't store dates in strings, it's asking for trouble.
使用
strip_attributes
gem:https://github.com/ rmm5t/strip_attributes
Use the
strip_attributes
gem:https://github.com/rmm5t/strip_attributes
我只是有一个在验证之前运行的过滤器,并删除所有参数以修剪它们。如果你把它放在你的基本控制器类上,你只需设置它并忘记它。
I'd just have a filter that runs before validation and tears through all of the params to trim them. If you put it on your base controller class, you just set it and forget it.
事实上,这也让我有点恼火 - 所以我写了这个
https://github.com/omarqureshi/AR- stripper
迟早会将其发布为 gem,但同时只需
在您的 Gemfile 中即可
Indeed, this annoyed me a little too - so I wrote this
https://github.com/omarqureshi/AR-stripper
will publish this as a gem sooner or later but in the meantime just
in your Gemfile will do
您还可以使用回调来去除空白而不使用 gem。
You could also use a callback to strip the whitespace without using a gem.