0

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
Artem Halas
  • 153
  • 1
  • 2
  • 15

1 Answers1

1

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)

Ivan Kolmychek
  • 1,261
  • 1
  • 9
  • 17
  • Yes, you are right, that `update_column`doesn't call callbacks. You are probably right that a better solution would be to make this operation in a controller and not in a model. Thanks a lot! – Artem Halas Jan 13 '15 at 11:38
  • @ArtemGalas I meant [`after_save` ActiveRecord callback in the model](http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html), not in the controller. ;) – Ivan Kolmychek Jan 13 '15 at 13:17