Rails 3资源路由,以param作为前缀

时间:2011-01-18 19:18:40

标签: ruby-on-rails ruby-on-rails-3 parameters routes

我的 rails 3 app Apache / mod_proxy 服务器的后台运行。

在rails应用中,存在必填前缀 :site_pin

在Apache中,我有以下内容来抽象我的前缀:

ServerName example.com

ProxyRequests Off
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass / http://localhost:3000/site/example/
ProxyPassReverse / http://localhost:3000/site/example/

<Location />
    Order allow,deny
    Allow from all
</Location>

在我的我的routes.rb中,我有以下内容:

resources :products

#RESTful fix
match 'site/:site_pin/:controller/', :action => 'index', :via => [:get]
match 'site/:site_pin/:controller/new', :action => 'new', :via => [:get]
match 'site/:site_pin/:controller/', :action => 'create', :via => [:post]
match 'site/:site_pin/:controller/:id', :action => 'show', :via => [:get]
match 'site/:site_pin/:controller/:id/edit', :action => 'edit', :via => [:get]
match 'site/:site_pin/:controller/:id', :action => 'update', :via => [:put]
match 'site/:site_pin/:controller/:id', :action => 'destroy', :via => [:delete]

一切都运行正常,但是任何人都有更好的解决方案来删除此修复并使routes.rb更干净?

1 个答案:

答案 0 :(得分:17)

scope对此非常有效。将您在routes.rb上面发布的内容替换为:

scope 'site/:site_pin' do
  resources :products
end

现在,运行rake:routes,你会看到以下输出:

    products GET    /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"index"}
             POST   /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"create"}
 new_product GET    /site/:site_pin/products/new(.:format)         {:controller=>"products", :action=>"new"}
edit_product GET    /site/:site_pin/products/:id/edit(.:format)    {:controller=>"products", :action=>"edit"}
     product GET    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"show"}
             PUT    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"update"}
             DELETE /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"destroy"}

:site_pin将以params[:site_pin]的形式提供。

当然,您可以将其他资源和路由添加到范围块中;所有这些都将以site/:site_pin为前缀。