如何使用friendly_id从URL中删除特定单词。红宝石在铁轨上

时间:2018-06-23 11:57:27

标签: ruby-on-rails ruby regex friendly-url friendly-id

我在我的Rails应用程序中使用friendly_id,并注意到它以字词逐词的形式出现。我想知道是否有一种方法可以解析包含与SEO不相关的单词(例如“ and”和“ for”)的信息。我已经尝试过一些yaml_str,但是我什至不确定它是否适用于REGEX

在我的应用程序记录(模型)中:

friendly_id

我绝对不是一个正则表达式的向导,我希望对此有所帮助,谢谢。

P.S。我的to_slug方法甚至适用于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 吗?我不能说出宝石是否已经执行了所有这些动作,谢谢!

1 个答案:

答案 0 :(得分:0)

您将要查看friendly_id文档,其中提供了有关Working With 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属性以正确呈现页面。

希望这会有所帮助。