Search code examples
ruby-on-railsrubyfriendly-urlfriendly-id

Understanding slug_candidates method in Rails model


I am trying to create pretty URLs in my Rails app. I could not understand what is happening inside the #slug_candidates method in the model.

class News < ApplicationRecord
  friendly_id :slug_candidates, use: [:slugged, :finders, :history]
  def slug_candidates 
    [:title,
      [:title, :id]
    ] 
  end
end

Also found a similar method in an answer:

def slug_candidates
  [
    :name,
    [:name, 2],
    [:name, 3],
    [:name, 4],
    [:name, 5],
    [:name, 6],
    [:name, 7]
  ]
end

Can someone provide a brief explanation of what the method does?


Solution

  • If we have 2 news having the same title, the slugs will be the same. So we can't identify them. For example:

    New.all
    # => [#<New id: 1, tile: "Title">, #<New id: 2, tile: "Title">]
    
    # Without `slug_candidates`
    New.first # => URL: "news/title"
    New.second # => URL: "news/title"
    # => We cannot find the second one.
    

    Now slug_candidates provides a list of variants and FriendlyId will go over that list until it finds a slug that is not already taken.

    # With `slug_candidates`
    def slug_candidates 
      [:title, [:title, :id]]
    end
    
    New.first # => URL: "news/title"
    New.second # => URL: "news/title-2"