fabianraf
fabianraf

Reputation: 155

How do I set slug limit using friendly_id gem?

I'm using friendly_id (4.0.10.1) and this is my class:

class Article < ActiveRecord::Base

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

end

How do I set a 49 characters limit for the slug field? The Gem works fine, it's just that I need to set this 49 limit managed by the gem and not by adding an extra step on the code.

Upvotes: 1

Views: 773

Answers (3)

Alexander Babushkin
Alexander Babushkin

Reputation: 1

I know it's been a long time. But maybe my example will help somebody

class Article < ActiveRecord::Base
  extend FriendlyId
  SLUG_LIMIT = 49

  friendly_id :slug_candidates, use: %i[slugged finders], slug_limit: 49

  class << self
    def normalize_friendly_id(text)
      text = cut_text(text) if text.length > SLUG_LIMIT
      text.to_slug.transliterate(:russian).normalize.to_s
    end

    def cut_text(text)
      counter_string = " #{text.split(" ").pop}"
      end_index = SLUG_LIMIT - 1 - counter_string.length
      text = text[0..end_index]

      text + counter_string
    end
  end

  def slug_candidates
    [
      :name,
      %i[name slug_counter]
    ]
  end

  def slug_counter
    self.class.where("lower(name) = ?", name.downcase).count + 1
  end
end

Upvotes: 0

Kashiftufail
Kashiftufail

Reputation: 10885

This is the best solution

 friendly_id :slug_candidates, use: :slugged

 def slug_candidates
  [
    :name,
    [:name, :city],
    [:name, :street, :city],
    [:name, :street_number, :street, :city]
  ]
 end 

More info here https://www.rubydoc.info/github/norman/friendly_id/FriendlyId/Slugged

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

You can use Active Record validations. For example, validates_length_of, either on the slug itself, or if the value is coming from a column, then on the column.

Another solution is here

def normalize_friendly_id(string)
  super[0..49]
end

I found these through a Google search just now.

https://github.com/norman/friendly_id/issues/190

Upvotes: 0

Related Questions