rb-
rb-

Reputation: 2365

Enabling history after using friendly_id for a while

I'm trying to add history to an existing production site. I hadn't previously generated the friendly_id migration so after adding it and changing use: :sluggable to use: [:sluggable, :history] to my model, my ability to Model.friendly.find... is gone on any objects that were in the model before I made this change.

What's the best way to address this. Should I just loop through and .save on every record in my model during the migration? That's all I've thought of doing so far. Not sure if that would work, but there must be a better way.

Update

What I mentioned in my original question is how I went about it. It seems clumsy, but it worked. I'd still love a better answer if one is out there.

# Added this to friendly_id migration
class CreateFriendlyIdSlugs < ActiveRecord::Migration
  def up
    Model.all.each do |m|
      m.save
    end
  end
end

Upvotes: 4

Views: 361

Answers (1)

David Yu
David Yu

Reputation: 11

This should work for both mysql and postgresql (which doesn't have INSERT IGNORE)

def up
  execute <<-SQL
    INSERT INTO friendly_id_slugs
      (slug, sluggable_id, sluggable_type, created_at)
    SELECT m.slug, m.id, 'Model', NOW()
    FROM models m
    LEFT OUTER JOIN friendly_id_slugs f ON f.sluggable_id = m.id
    WHERE m.slug IS NOT NULL AND LENGTH(m.slug) > 0 AND f.id IS NULL
  SQL
end

Upvotes: 1

Related Questions