Ruby on rails 3.2 Rails:未生成包含下划线的段塞

Ruby on rails 3.2 Rails:未生成包含下划线的段塞,ruby-on-rails-3.2,slug,Ruby On Rails 3.2,Slug,我需要在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*/, " a

我需要在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

e、 g.品牌名称中的“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

我不明白这里出了什么问题。有人能帮忙吗?

您得到一个
档案存在
错误,然后ActiveRecord执行
回滚
。您没有发布您的模型,但我猜有某种独特的验证触发回滚,因为已经有一个条目包含这些值。

您是对的。存在验证问题。现在解决了。谢谢