Change the unique generated title names of friendly-id

随声附和 提交于 2019-12-03 15:43:19

Check the documentation for the latest version of friendly_id:

A new "candidates" functionality which makes it easy to set up a list of alternate slugs that can be used to uniquely distinguish records, rather than appending a sequence.

Example straight from the docs:

class Restaurant < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  # Try building a slug based on the following fields in
  # increasing order of specificity.
  def slug_candidates
    [
      :name,
      [:name, :city],
      [:name, :street, :city],
      [:name, :street_number, :street, :city]
    ]
  end
end

UUID

The problem you're alluding to is the way in which friendly-id appends a hash (they call it a UUID) to duplicate entries:

Now that candidates have been added, FriendlyId no longer uses a numeric sequence to differentiate conflicting slug, but rather a UUID (e.g. something like 2bc08962-b3dd-4f29-b2e6-244710c86106). This makes the codebase simpler and more reliable when running concurrently, at the expense of uglier ids being generated when there are conflicts.

I don't understand why they have done this, as it goes against the mantra of friendly ID, but nonetheless, you have to appreciate that's how it works. And whilst I don't think the slug_candidates method above will prove any more successful, I do think that you'll be able to use something like a custom method to define the slug you wish

--

You'll want to read this documentation (very informative)

It says there are two ways to determine the "slug" your records are assigned, either by using a custom method, or by overriding the normalize_friendly_id method. Here's my interpretation of both of these for you:

Custom Method

#app/models/project.rb
Class Project < ActiveRecord::Base
   extend FriendlyID
   friendly_id :custom_name, use: :slugged

   def custom_name
     name = self.count "name = #{name}"
     count = (name > 0) ? "-" + name : nil 
     "#{name}#{count}"
   end
end

Normalize_Friendly_ID

#app/models/project.rb
Class Project < ActiveRecord::Base
   extend FriendlyID
   friendly_id :name, use: :slugged

   def normalize_friendly_id
     count = self.count "name = #{name}"
     super + "-" + count if name > 0
   end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!