首页 > 解决方案 > 如何使用 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 是否已经执行了所有这些操作,谢谢!

标签: ruby-on-railsrubyregexfriendly-urlfriendly-id

解决方案


您将要查看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模型中的属性以正确呈现页面。

希望这可以帮助。


推荐阅读