Question

I have a photo at the URL:

www.mysite.com/here-is-my-url

I have created a replacement for this photo but I want the old url to point to the new resource. I.e. the new resource is www.mysite.com/new-url but I want the URL to be www.mysite.com/here-is-my-url and for the old resource, I want to change it to something else altogether.

I know it's best not to manually fiddle with the friendly_id slugs, BUT this is an emergency one-off type thing and I'm trying to figure out the most painless way to do this (preferably via the console).

Any thoughts? I basically need access to the friendly_id_slugs table via the console, but I get an uninitialized constant error when I try to do FriendlyIdSlug.all .

Was it helpful?

Solution

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

add that to your model. name_change? should be [whatever your column is that decides the slug]_changed?

OTHER TIPS

Normally, there's no FriendlyIdSlug model/table, so getting uninitialized constant error on FriendlyIdSlug.all is kind of Ok.

When you add friendly_id to a resource, it just adds a slug field, that's being regenerated based on the specified field (title in your case) whenever it's blank. If the standard slug generation procedure gives you a slug which is not unique within the corresponding table, friendly_id alters it by adding --n (n integer) to it until it becomes unique.

That said, in order to resolve your situation you have to

  1. Change the title of the old object, set its slug to nil, save.
  2. Set the slug of the new object to nil, save.
  3. Change the title of the old object back if needed.

For example, if your model is Photo, it will be something like this in your console:

old = Photo.find('here-is-my-url')
new = Photo.find('here-is-my-url--2')
old.title = 'Here is my OLD URL'
old.slug = nil
old.save
new.slug = nil
new.save

There is a way to do this through the console. I have a site on production that I needed to update one friendly-id slug too, due to the fact that we had been promoting a URL with printed flyers. Archaic, yes I know. Try this:

Model.all (find to find the id of the slug you'd like to change)
u = Model.find(id) (integer of the id you'd like to change)
u.slug = nil
u.slug = 'slug-of-your-choice'
u.update_attribute(:slug, 'slug-of-your-choice')

Now if you check Model.all, you'll see your Model object with the manually updated slug. Also tested on the live site. Using u.save after updating the slug did not work for me. Also, the update_attribute style used here is Rails 3, so use Rails 4 syntax for Rails 4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top