Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 resource route with param as prefix

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/:site_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?

like image 502
Diego Rocha Avatar asked Dec 04 '22 09:12

Diego Rocha


1 Answers

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.

like image 128
vonconrad Avatar answered Dec 21 '22 22:12

vonconrad