自定义slug方法未执行代码?Ruby on Rails FriendlyId问题
自定义FriendlyId Slug时移除指定内容无效的问题
我需要对博客文章的URL做以下修改:
- 解析并移除URL中的"an-"实例
- 若URL以"the-"为前缀,则移除该前缀
我写的相关代码如下:
class BlogPost < ApplicationRecord extend FriendlyId friendly_id :custom_slug, use: :history ... def custom_slug a = "#{title.to_s}" # 目标:从URL中移除单词an # 要移除的单词放在"/\b和\b/"之间 # "#{title}".gsub! "/\ban\b/", "" a.gsub! "/\ban-\b/", "" # 若slug以"the-"开头则移除该前缀 if a.start_with?("the-") a.slice! "the-" end return a end end
测试标题为"the example of an the post"时,FriendlyId转换后的URL是"/the-example-of-an-the-post",但我期望得到"/example-of-the-post"。目前自定义代码没有生效,直接返回了原字符串。我认为.slice!的逻辑是可行的,但不确定整体代码哪里出了问题。
更新:问题解决方法
根据建议,我做了以下修改解决了问题:
- 将字符串转为小写:
a = "#{title.to_s.downcase}" - 替换有问题的正则表达式,改用简单的字符串替换:
if a.include?(" an ") a.gsub! " an ", " " end - 修正判断逻辑,针对原标题的空格分隔形式处理,而非slug的连字符形式:
if a.start_with?("the ") a.slice! "the " end
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

