Best way to generate slugs (human-readable IDs) in Rails

前端 未结 12 830
北荒
北荒 2020-11-30 18:05

You know, like myblog.com/posts/donald-e-knuth.

Should I do this with the built in parameterize method?

What about a plugin? I could imagine a plugin being n

12条回答
  •  时光取名叫无心
    2020-11-30 19:04

    Here is what I use:

    class User < ActiveRecord::Base
      before_create :make_slug
      private
    
      def make_slug
        self.slug = self.name.downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')
      end
    end
    

    Pretty self explanatory, although the only problem with this is if there is already the same one, it won't be name-01 or something like that.

    Example:

    ".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')
    

    Outputs: -downcase-gsub-a-z1-9-chomp

提交回复
热议问题