Rails4 Friendly_id Unique Slug Formatting

前端 未结 4 1946
抹茶落季
抹茶落季 2021-02-15 22:15

I am using friendly_id gem for slugging my models. Since the slug has to be unique when i enter the same data to check i get a long hashed appending in the slug.



        
4条回答
  •  情书的邮戳
    2021-02-15 23:11

    So if anyone comes across this at some point, I have an update I would have preferred to put as a comment in tirdadc's comment, but I can't (not enough reputation). So, here you go:

    Tirdadc's answer is perfect, in theory, but unfortunately the id of an object isn't yet assigned at the point slug_candidates is called, so you need to do a little trickery. Here's the full way to get a slug with the id of the object in there:

    class YourModel < ActiveRecord::Base
      extend FriendlyId
      friendly_id :slug_candidates, use: :slugged
      after_create :remake_slug
    
      # Try building a slug based on the following fields in
      # increasing order of specificity.
      def slug_candidates
        [
          :name,
          [:name, :id],
        ]
      end
    
      def remake_slug
        self.update_attribute(:slug, nil)
        self.save!
      end
    
      #You don't necessarily need this bit, but I have it in there anyways
      def should_generate_new_friendly_id?
        new_record? || self.slug.nil?
      end
    end
    

    So you're basically setting the slug after the creation of the object and then after the object is done being created, you nil out the slug and perform a save, which will reassign the slug (now with the id intact). Is saving an object in an after_create call dangerous? Probably, but it seems to work for me.

提交回复
热议问题