如何在Rails 3中处理传统的param基本URL?

时间:2012-02-24 16:14:58

标签: ruby-on-rails-3 routes

我有一个使用以下URL结构的遗留PHP应用程序

/product_info.php?products_id=YYY

其中YYY是产品的ID,产品型号的id字段。

我现在正在使用Rails重写此应用程序,并且出于搜索引擎优化的目的,我现在必须保留此URL结构。

如何将上述URL路由到ProductsController的show动作?我应该使用Apache的mod_rewrite将其重写为/ products /:id还是可以使用Rails的路由器来实现?我希望能够使用路径助手,以便product_path(@product)返回给我/product_info.php?products_id=YYY(再次用于SEO)

1 个答案:

答案 0 :(得分:3)

这实际上比我预期的要简单明了。

首先,设置您的路线:

# config/routes.rb
MyApp::Application.routes.draw do
  match '/product_info' => 'products#show'
end

由于Rails通常不提供PHP文件,因此您需要为.php创建MIME类型处理程序:

# config/initializers/mime_types.rb
Mime::Type.register_alias 'text/html', :php

设置products#show操作,根据网址参数查找产品。由于您将php MIME类型别名为text/html,因此您无需执行任何特殊操作来呈现“PHP”视图:

# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:products_id])
  end
end

您必须手动创建product_path辅助方法,因为您没有使用RESTful路由:

# app/helpers/products_helper.rb
module ProductsHelper
  def product_path(product)
    "/product_info.php?products_id=#{product.id}"
  end
end

现在只需创建您的视图:

# app/views/products/show.php.erb
<%= link_to @product.name, @product %>