Question

I want to be able to better understand rails routes file, but I can't figure it out by myself since it's too complex.

Basically I have 3 controllers. They are: Admin, ManageProduct and ManageProductCategory (I have 2 models: Product, ProductCategory and model ProductCategory has_many/belongs_to products relationship)

Admin controller actions:

  • index (redirects to login)
  • login
  • logout
  • attempt

ManageProduct controller actions:

  • index
  • CRUD (delete, edit, show, list) for model product

ManageProductCategory

  • index
  • CRUD (delete, edit, show, list) for model product_category

I want to be able to manage my application routes so that if I type in the browser:

mywebsite/admin
mywebsite/admin/login
mywebsite/admin/logout
mywebsite/admin/manage_product
mywebsite/admin/manage_product_category/1
mywebsite/admin/manage_product/delete
mywebsite/admin/manage_product/10

And so on...

The problem is I can't figure out how to setup my route files so that rails understand that admin/manage_product is not a admin controller action...

NOTICE: Everything is already working (CRUD for 2 models and links to action via standard not recommended route

match ':controller(/:action(/:id(.:format)))'

Really appreciate your help and attention

Regards

Was it helpful?

Solution

What you need is a namespace

# Rails 2.3.x
map.namespace :admin do |admin|
  map.resources :products
end

# Rails 3
namespace "admin" do
  resources :products
end

This will give you the following URL helper methods:

admin_products_path    GET  { :controller => "admin/products", :action => "index" }
new_admin_product_path GET  { :controller => "admin/products", :action => "new" }
admin_products_path    POST { :controller => "admin/products", :action => "create" }

To generate a controller under the admin namespace you need to do the following under your console:

$ rails generate controller admin/products

This will generate for you the admin directory under app/controllers and then the products.rb file:

class Admin::ProductsController < ApplicationController
end

Now about, the login under the admin namespace you can set it up with Devise, which is a gem for authentication. You can go further in here: https://github.com/plataformatec/devise/wiki/_pages

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top