开发者

Rails 3 resource route with param as prefix

开发者 https://www.devze.com 2023-02-05 22:22 出处:网络
My rails 3 app runs in the background of a Apache/mod_proxy server. In the rails app exists a mandatory prefix :site_pin

My rails 3 app runs in the background of a Apache/mod_proxy server.

In the rails app exists a mandatory prefix :site_pin

In Apache the i have the following to abstract my prefix:

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>

In my my routes.rb i have the following:

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/:s开发者_运维百科ite_pin/:controller/:id', :action => 'update', :via => [:put]
match 'site/:site_pin/:controller/:id', :action => 'destroy', :via => [:delete]

Everything works fine in this way, but anyone has a better solution for remove this fix and make the routes.rb more clean?


scope would be very effective for this. Replace what you posted above in your routes.rb with:

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

Now, run rake:routes in and you should see the following output:

    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 will be available as params[:site_pin].

Naturally, you'll be able to add other resources and routes into the scope block; all of which will be prefixed with site/:site_pin.

0

精彩评论

暂无评论...
验证码 换一张
取 消