Search code examples
ruby-on-rails-3.2slug

Rails: slug containing underscores not getting generated


I an running a script on rails console to generate slug for profile brand names. This is my script:

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

It is working perfectly for strings that do not contain underscores. But it doesnt generate slug for strings that contains underscore.

e.g. in brand name is "Kalpana's_Creations", slug of this brand name is "nil", which should be "kalpanas_creations"

This is what i see when rails console runs the script:

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

I am not getting whats going wrong here. Can any body help?


Solution

  • You get an Profile Exists error and after that ActiveRecord does a ROLLBACK. You didn't post your model but I guess that there is some sort of unique validation which triggers the rollback because there is already an entry with these values.