ruby-on-rails - 如何使用 friendly_id 从 URL 中删除特定单词 | 铁轨上的红宝石
问题描述
我正在为我的 rails 应用程序使用 friendly_id,并注意到它逐字逐句地放入了一个 slug 中。我想知道是否有一种方法可以从包含非 SEO 相关词(例如“and”和“for”)中解析 slug。我已经尝试了一些REGEX
,但我什至不确定它是否适用于friendly_id
.
在我的申请记录(模型)中:
def to_slug(param=self.slug)
# strip the string
ret = param.strip
#blow away apostrophes
ret.gsub! /['`]/, ""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# replace all non alphanumeric, periods with dash
ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'
# replace underscore with dash
ret.gsub! /[-_]{2,}/, '-'
# convert double dashes to single
ret.gsub! /-+/, "-"
# strip off leading/trailing dash
ret.gsub! /\A[-\.]+|[-\.]+\z/, ""
ret
end
我绝对不是正则表达式方面的专家,我希望对此有所帮助,谢谢。
PS我的 to_slug 方法是否适用于friendly_id
?我不知道 gem 是否已经执行了所有这些操作,谢谢!
解决方案
您将要查看friendly_id文档,它为您提供有关使用Slugs的更多信息
您的模型可能看起来像这样(更新它以适应您的正则表达式需求):
class SampleModel < ActiveRecord::Base
extend FriendlyId
friendly_id :custom_friendly_id
# Insert more logic here
def custom_friendly_id
your_column.gsub! /\s*&\s*/, " and "
end
end
我为之前的应用程序执行了此操作,但遇到了旧数据的路由问题。我最终添加:slugged
到我的friendly_id
命令:friendly_id :custom_friendly_id, use: :slugged
. 然后运行迁移脚本来更新slug
模型中的属性以正确呈现页面。
希望这可以帮助。
推荐阅读
- python - 我无法使用 pyttsx3 模块更改声音!任何索引都只返回 DAVID
- javascript - jquery Select2 函数中的搜索功能不起作用?
- python - 可以使用python将切片器添加到excel中吗
- firebase - Firebase 托管网站显示“此网站无法提供安全连接”
- c++ - 'View v' 类型不完整,无法定义 C++
- ios - 在 swift5 中:iPad 上的弹出窗口大小合适,但在 iPhone 上却使用全屏?
- jdbc - PostgreSQL JDBC 接收器引发错误 null(Array) 类型没有到 SQL 数据库列类型的映射
- c - 关于使用命令行设置vino
- c# - 使用 ContentControl 将图片附加到 Word
- javascript - PHP base64_decode 无法解码完整的 javascript btoa 编码