删除非法字符的助手?

发布于 2024-09-14 21:29:22 字数 367 浏览 3 评论 0原文

我正在使用用户输入字符串来创建 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ左 2024-09-21 21:29:22

您可以使用 ActiveSupport 的 parameterize 方法:

def to_param
  name.parameterize
end

You can use ActiveSupport's parameterize method:

def to_param
  name.parameterize
end
爱本泡沫多脆弱 2024-09-21 21:29:22

您可以考虑使用 to_slug 插件。另请参阅此相关问题

You might consider the to_slug plugin for this. See also this related question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文