Guest User

Untitled

a guest
Aug 15th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. Rails redirect from old URL to a new one that using slug
  2. module ApplicationHelper
  3. def product_path(product)
  4. unless product.category.nil?
  5. cat = product.category
  6. if cat.ancestry_depth.eql?(2)
  7. product_long_path cat.root, cat.parent, cat, product
  8. else
  9. product_short_path cat.parent, cat, product
  10. end
  11. end
  12. end
  13. end
  14.  
  15. get "/(*root_id)_(*subcategory_id)_(*category_id)_(*id)" => "products#show", :as => :product_long
  16. get "/(*root_id)_(*category_id)_(*id)" => "products#show", :as => :product_short
  17.  
  18. def show
  19. @product = Product.find_by_slug params[:id]
  20. cat = @product.category
  21.  
  22. raise NotFound unless cat.slug.eql?(params[:category_id]) and cat.root.slug.eql?(params[:root_id])
  23. raise NotFound if cat.ancestry_depth.eql?(2) and !cat.parent.slug.eql?(params[:subcategory_id])
  24. end
  25.  
  26. @product = Product.find_by_slug params[:id]
  27. if @product.nil?
  28. @product = Product.find params[:id]
  29. redirect_to @product.redirect_string and return
  30. end
  31.  
  32. def redirect_string
  33. if category.ancestry_depth.eql?(2)
  34. "/#{category.root.slug}_#{category.parent.slug}_#{category.slug}_#{slug}"
  35. else
  36. "/#{category.parent.slug}_#{category.slug}_#{slug}"
  37. end
  38. end
Add Comment
Please, Sign In to add comment