How to redirect old urls to new friendly_id generated urls in rails app?

本小妞迷上赌 提交于 2020-01-17 08:55:29

问题


I prettified my urls using friendy_id. My old url used look like below:

localhost:3000/search?category_id=208

Now it looks like this:

localhost:3000/search?category_id=metal-processing-and-machine-tool

My controller is this:

def search_equipments
    begin
      if (params.keys & ['category_id', 'sub_category', 'manufacturer', 'country', 'state', 'keyword']).present?
        if params[:category_id].present?
          @category = Category.active.friendly.find_by_friendly_id params[:category_id]
        else
          @category = Category.active.friendly.find_by_friendly_id params[:sub_category] if params[:sub_category].present?
        end
        @root_categories = Category.active.roots
        @sub_categories = @category.children.active if params[:category_id].present?
        @sub_categories ||= {}
        @countries = Country.active.all
        @manufacturers = Manufacturer.active.all
        @states = State.active.where("country_id = ?", params[:country]) if params[:country].present?
        @states ||= {} 
        unless params[:category_id].present? && params[:sub_category].present?
          params[:category_id] = @category.id if params[:category_id].present?
          params[:sub_category] = @category.id if params[:sub_category].present?
        end   
        @equipments = Equipment.active.filter(params.slice(:manufacturer, :country, :state, :category_id, :sub_category, :keyword)).order("#{sort_column} #{sort_direction}, created_at desc").page(params[:page]).per(per_page_items)               
      else
        redirect_to root_path
      end
    rescue Exception => e
      render :file=>"#{Rails.root}/public/404.html",:status=>404
    end

  end

Right now I am redirecting old urls to 404 page. But instead I would like the old urls to redirect to new urls. How can I achieve this? I gone through some solutions. But my big controller method is making it complex enough to follow those solutions.


回答1:


You can try this:

if params[:category_id].present? and params[:category_id].to_s !~ /\D/
       category = Category.find_by_id(params[:category_id])
       return redirect_to search_equipments_path(request.query_parameters.merge(category_id: category.name.parameterize)) if category.present?

If you have sub-category, you can use same condition just changing params category to sub-category.




回答2:


add this to your method search_equipments beginning

   if params[:category_id].present? and params[:category_id].to_s !~ /\D/
      category = Category.find_by_id(params[:category_id])
      return redirect_to search_equipments_path(category_id: category.name.parameterize) if category.present?
   end


来源:https://stackoverflow.com/questions/43626580/how-to-redirect-old-urls-to-new-friendly-id-generated-urls-in-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!