Reputation: 2227
I have a Page model in my rails 4 app. It has an :permalink attribute that is used so that when someone goes to "mysite.com/pages/page-name", the controller finds the Page with "page-name" as the permalink and then shows the view.
pages_controller.rb:
def show
@page = Page.find_by_permalink!(params[:id])
end
After a few months of the site being up, I want to change the permalink of a certain page, however I don't want to lose all the incoming links. I'm thinking I would do this.
First I'd add_colum :new_permalink to the Page model. Then if this :new_permalink attribute was anything but nil or blank, it would pull up a new page in the controller like this:
def show
@page = Page.find_by_permalink!(params[:id])
if [email protected]_permalink.blank?
@page = Page.find_by_permalink!(@page.new_permalink)
end
end
This works, but the url in the browser still shows the old URL. I suppose this might not be so bad, but I think I'd like it to actually forward to the new page. Perhaps, instead of "new_permalink" it should be a new url and actually do a redirect? What would be your best solution for this? And could I make it a 301 redirect?
Upvotes: 0
Views: 162
Reputation: 7586
Yes, you should use a 301 redirect so that both the user and search engines would send the browser to the correct location.
def show
@page = Page.find_by_permalink!(params[:id])
if @page.new_permalink.present?
redirect_to page_path(@page.new_permalink), status: :moved_permanently
return
end
end
Upvotes: 1