如何在rails应用程序中将特定的url模式发送到404?

时间:2017-05-04 08:58:43

标签: ruby-on-rails

在我的rails应用程序中,我正在生成一个url,其正确的模式如下:

https://example.com/equipment_details/slug

这是网址应该是索引的谷歌。但由于使用javascript进行分页实现,平台上还有另一个活动网址如下:

http://localhost:3000/equipment_details/slug?page=2

控制器方法如下:

class EquipmentsController < ApplicationController
  def equipment_details
    @equipment = Equipment.friendly.active.includes(:country, :manufacturer, :category, :user).find(params[:id])
    if @equipment
      @products = @equipment.category.equipments.active.where.not("equipment.id = ?", @equipment.id)
      @countries = Country.active.all
      @states = State.active.all
      @cities = City.active.all
      @services = Service.active.where("category_id = ? AND sub_category_id = ? AND country_id = ? AND state_id = ? AND city_id = ?", @equipment.category_id, @equipment.sub_category_id, @equipment.country_id, @equipment.state_id, @equipment.city_id)
      respond_to do |format|
        format.js
        format.html
        format.pdf do
          render :pdf => "vendaxo_#{@equipment.title}",
                 :layout => 'equipment_details_pdf.html.erb',
                 :disposition => 'attachment'
        end
      end
    else
      flash[:error] = "Equipment not found."
      redirect_to root_path
    end
  end
end

除了页脚中的javascript分页内容外,两个url上的主要内容基本相同。这导致了SEO优化中的问题。如何将带有第二种模式的网址发送到?page=2404页面?有没有办法从rails routes文件中执行此操作?

2 个答案:

答案 0 :(得分:1)

如果您特别想要查找名为page的查询参数并引发异常以激活404响应(如果该请求不是来自您的javascript的AJAX调用),您可以在之前执行此操作您EquipmentDetailsController(或其他任何名称)的行动。

class EquipmentDetailsController < ApplicationController
  before_action :send_to_404, only: [:name] # or whatever the action is called

  def send_to_404
    if !request.xhr? && !params[:page].nil?
      raise ActionController::RoutingError.new('Not Found')
    end
  end  
end

答案 1 :(得分:0)

您可以在params[:page] == 2

时使用404发送
render plain: "record was not found", status: :not_found

但是,当您不希望Google为该网页编制索引时(实际上确实存在),您不应该只发送404。 Google evaluates javascript these days as well

考虑添加noindex header to the page和/或使用a canonical url reference

<meta name="robots" content="noindex">
<link rel="canonical" href="https://example.com/equipment_details/name">