删除非法字符的助手?
我正在使用用户输入字符串来创建 url,并且我只希望 url 包含小写字母和连字符
例如 example.com/this-is-a-url
在我的模型中,到目前为止我已添加:
def to_param
name.downcase.gsub(" ", "-")
end
这使其小写并连字符。如何删除所有非法字符,例如 '/"$£%& 等?正则表达式可能是答案,但是 Rails 中是否已经内置了用于此目的的内容?
也许我不执行上述操作,而是这样做应该创建一个验证来确保“名称”只是空格和字母?是否有为此目的内置的东西?
I am using a user input string to create a url and I only want the url to contain lowercase letters and hyphens
e.g. example.com/this-is-a-url
In my model, I have added so far:
def to_param
name.downcase.gsub(" ", "-")
end
This makes it lowercase and hyphenated. How can I remove all illegal characters, such as '/"$£%& and so on? A regular expression might be the answer but is there something built in for this purpose already in Rails?
Perhaps instead of doing the above, I should create a validation that makes sure that 'name' is only spaces and letters? Is there something built in for this purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 ActiveSupport 的
parameterize
方法:You can use ActiveSupport's
parameterize
method:parameterize
API documentation您可以考虑使用
to_slug
插件。另请参阅此相关问题。You might consider the
to_slug
plugin for this. See also this related question.