Rails gsub 问题
创建新帖子时,如何在控制器中将“”和“_”替换为“-”?
我有以下表单字段: 标题 网址 content
我想在 url 字段上执行 gsub。
谢谢...
How can i replace " " and "_" with "-" in my controller when creating a new post?
I have the following form fields:
title
url
content
I want to execute the gsub on the url field.
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请记住,从 URL 中删除空格和“_”是不够的,因为还有一些其他字符可能会破坏您的 HTML 代码,甚至导致脚本注入。
<>'"/\
。我建议传递所有字母和数字 - 其他所有内容都会转换为
-
。控制器保持不变。
Remember that getting rid of space and "_" from URL is not enough as there are some other characters which my break your HTML code and even cause script injection.
<>'"/\
.I suggest passing all letters and numbers - everything else translate to
-
.Controller is unchanged.
如果你想打败这个标题,那么你可能会发现 Norman 的Friendly_id 有一些用处:
http://github.com /norman/Friendly_id
它会为您创建永久链接,因此您无需担心应用程序中网址的重复或生成。它还将与 ActiveRecord 集成以覆盖查找方法。
If you're trying to slug the title, then you may find Norman's friendly_id of some use:
http://github.com/norman/friendly_id
It'll take care of creating permalinks for you, so you won't need to worry about duplication or generation of the url in your app. It'll also integrate with ActiveRecord to override the find methods.
title.gsub(" ","-").gsub("_","-")
title.gsub(" ","-").gsub("_","-")
title.gsub(/[\s_]+/, '-').strip
title.gsub(/[\s_]+/, '-').strip