如何将旧网址重定向到rails app中新的friendly_id生成的网址?

时间:2017-04-26 06:28:44

标签: ruby-on-rails friendly-id

我用friendy_id美化了我的网址。我使用的旧网址如下所示:

localhost:3000/search?category_id=208

现在看起来像这样:

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

我的控制器是:

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

现在我将旧网址重定向到404页面。但相反,我希望旧网址重定向到新网址。我怎样才能做到这一点?我经历了一些解决方案。但我的大控制器方法使其足够复杂以遵循这些解决方案。

2 个答案:

答案 0 :(得分:1)

将此添加到方法search_equipments开头

   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

答案 1 :(得分:1)

你可以试试这个:

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?

如果您有子类别,则只需将params category更改为sub-category即可使用相同的条件。