Search code examples
ruby-on-railsroutesruby-on-rails-3.2slug

Rails + Using Friendly ID for slug generation and creating trouble while accessing from DB


Facing some strange problem with respect to Slug in Rails

Loading development environment (Rails 3.2.13)
2.1.2 :001 > Tutorial.last
  Tutorial Load (0.7ms)  SELECT "tutorials".* FROM "tutorials" 
  ORDER BY "tutorials"."id" DESC LIMIT 1

 => #<Tutorial id: 3, title: "Populating the Database’s with seeds.rb",
    state: "Publish", content_introduction: "<p>Demo Data</p>\r\n", 
    slug: "populating-the-database-s-with-seeds-rb"> 

2.1.2 :002 > Tutorial.last.slug
  Tutorial Load (0.6ms)  SELECT "tutorials".* FROM "tutorials" 
    ORDER BY "tutorials"."id" DESC LIMIT 1
 => "populating-the-database’s-with-seeds.rb" 

In database it show "-" by replacing special character but while accessing it gives as it.

Model

def slug
  title.strip.downcase.gsub(/[:,'"%^&*+=<>.`~]/,"").gsub("’","").gsub("  ", " ").gsub(" ", "-")
end

def to_param
  "#{slug}".parameterize
end

extend FriendlyId
friendly_id :title, use: [ :slugged, :history ]   

So while accessing the page using slug it gives error. Please have a look and suggest something.


Solution

  • There is a difference between what you see the value of slug in Tutorial.last and what you get in Tutorial.last.slug

    Tutorial.last fetches the last record from the table which is giving you the slug saved in the database, but Tutorial.last.slug is calling the slug method defined in your model, Tutorial.last is an object and using that object you are calling the slug method

    def slug
      title.strip.downcase.gsub(/[:,'"%^&*+=<>.`~]/,"").gsub("’","").gsub("  ", " ").gsub(" ", "-")
    end
    

    So comment out the above method and you will get the same results in both cases!

    Looks like the slug method which you have defined in your model is manipulating the title field to get the slug value, but as far as I know friendly_id gem itself handles it, so just comment out the slug method. It will solve your problem. Hope this helps!