Search code examples
ruby-on-railsrubyfriendly-urlslugfriendly-id

Friendly ID for duplicates


Let's say we have 2 posts with the same titles: "superheros". The first post should have url superheros-alternative-1 and the second one should have superheros-alternative-2. The problem is that when I am updating a title of one of these posts, the url should change for both of them. I mean if I change a title to "marvel", then the urls should become the following marvel-alternative-1 and marvel-alternative-2. Now I have the next code

class Post < ActiveRecord::Base

  before_update :update_slug

  def should_generate_new_friendly_id?
    slug.blank? || title_changed?
  end

  def update_slug
    title = Post.find(self.id).title
    Post.where(title:title).each do |post|
      post.update_column(:title,self.title)
    end
  end
end

Solution

  • You should not use update_column for this, because it will not trigger the callbacks, validations and such, so, friendly_id will not update your slug. Update the model object attribute and call .save instead.

    Also, you can update other records after you updated your regular one (in after_save callback) - there you will have access to original title and new one, without need to do additional Post.find(self.id)