Search code examples
ruby-on-railsslug

rails - a slug not updated after changed the record


I have a model:

class Page < ActiveRecord::Base
    has_ancestry
    validates :slug, :name, uniqueness: true, presence: true
    before_validation :generate_slug

    def to_param
        slug
    end

    def generate_slug
        name_as_slug = Russian.translit(name).parameterize
        if parent.present?
          self.slug = [parent.slug, (slug.blank? ? name_as_slug : slug.split('/').last)].join('/')
        else
          self.slug = name_as_slug if slug.blank?
        end
    end
end

My problem is that I can't update the slug after changed field "Name" of the record. For instance, if the slug was /page-1/page-1-1/page-1-1-1 for the Page with name: **"Page 1.1"** that after the change of name to Page Abrakadabra slug remains the same instead of /page-1/page-1-1/page-abrakadabra.

Sorry for my bad English.


Solution

  • It looks like your use of slug.blank? is preventing the change.

    How about something like this instead?

    def generate_slug
      name_as_slug = Russian.translit(name).parameterize
      return if name_as_slug == slug.split('/').last
      slug_elements = []
      slug_elements << parent.slug if parent.present?
      slug_elements << name_as_slug
      self.slug = slug_elements.join('/')
    end