我在 Rails 控制台上运行一个脚本来为配置文件品牌名称生成 slug。这是我的脚本:
class String
def to_slug
#strip the string
ret = self.strip.downcase
#blow away apostrophes
ret.gsub! /['`]/,""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
#replace all non alphanumeric, underscore or periods with hyphen
ret.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '-'
#convert double underscores to single
ret.gsub! /_+/,"_"
#strip off leading/trailing underscore
ret.gsub! /\A[_\.]+|[_\.]+\z/,""
ret
end
end
Profile.all.each do |profile|
if !profile.brand_name.nil? && profile.brand_name != profile.first_name
profile.slug = profile.brand_name.to_slug
profile.save
end
end
它非常适用于不包含下划线的字符串。但它不会为包含下划线的字符串生成 slug。
例如,品牌名称是“Kalpana's_Creations”,这个品牌名称的 slug 是“nil”,应该是“kalpanas_creations”
这是我在 rails 控制台运行脚本时看到的:
Profile Load (3.2ms) SELECT `profiles`.* FROM `profiles`
(0.2ms) BEGIN
Profile Exists (0.8ms) SELECT 1 AS one FROM `profiles` WHERE (`profiles`.`brand_name` = BINARY 'Kalpana\'s_Creations' AND `profiles`.`id` != 6) LIMIT 1
(0.2ms) ROLLBACK
我不明白这里出了什么问题。任何身体都可以帮忙吗?