Is there a gem that does this or is it baked in even? My understanding of things now is that anytime I change the path for a page (perhaps I do it for SEO) I need to create a new 301 redirect. Shouldn’t this be handled automatically?
If so, how is it handled automatically and how do I make use of it?
Thanks!!!
This is a rather complicated question and depends a lot on how your routes look right now. The simple answer is: no, this is not handled automatically by Rails.
The easiest way to handle redirects like this is in the
routes.rbfile, redirect from the old path to the new one. Something like this:You can learn more about this kind of redirect at the Rails routing guide.
If you’re changing just one instance of a product, then obviously this doesn’t make a whole lot of sense — you can’t do this for every changed object. In this case, we’ll assume that you aren’t using standard ID-based routing; if you were then this wouldn’t be a problem. (Since the ID wouldn’t change, instead it seems likely your routing is based off of a field that does change — like name or date or something.)
In this case, you probably want to extract the routing field away from whatever it currently is and into a slug column of its own. I recommend the really excellent friendly_id gem for this: it allows you to automatically generate slugs, and its history module allows you to perform lookups with an object’s old slug.
Then, you can look up an object by its ID, its slug, or any of its old slugs, if you find it necessary to do so.