views:

81

answers:

3

Hello!

I have this in routes.rb

map.namespace :admin do |admin|
  admin.resources :projects, :has_many => :products
end

What I would like to is to be able to set the something in the routes.rb file in order for me to use new action in the products controller. Actions added by hand after scaffolding.

I tried something like this

 map.namespace :admin do |admin|
   admin.resources :projects, :has_many => :products , :collection => {:plan => :get}
 end

plan being my new action in the products controller

Did not work and I have not find any good solutions anywhere. Please help.

A: 

Here you have some examples.

Your example should generate urls like: /admin/projects/plan. If you want to have url like /admin/projects/2/plan then use:

map.namespace :admin do |admin|
  admin.resources :projects, :has_many => :products , :member => {:plan => :get}
end

And don't forget to add plan method in your admin/products_controller.rb:

def plan
  ...
end

I'm not sure, but probably you will need to restart your server after changing routes to get it working.

klew
no need to restart in development environment, it will read new routes.rb
Vitaly Kushner
Thank you. What I needed was to be able to have an URL like this:/admin/projects/2/products/3/plan.
Radu
+1  A: 

As klew already pointed out you probably want a member action and not a collection action.

But before you go this route think if you really needed. adding custom actions is discouraged. You better stay within the constrains of the 7 CRUD operations. The way to do it is to add more controllers :)

For example if you have users controller and groups controller, then adding person into the group is not join_group action in the users controller, and not add_user action in the group controller, its a regular create action in memberships controller :).

and remember that controllers do not always correspond to models, and models not necessarily correspond to database tables, you can be more flexible.

Back to your case, I think you might want to just add a singleton resource nested inside the project resource like this

map.namespace :admin do |admin|
    admin.resources :projects, :has_many_products, :has_one => :plan
end

and implement :show action in the plans_controller, which should be mapped to /admin/projects/:project_id/plan

Vitaly Kushner
Thank you. The solution I was looking for was different. Simone's solution was what I needed.
Radu
A: 

Change

map.namespace :admin do |admin|
  admin.resources :projects, :has_many => :products
end

in

map.namespace :admin do |admin|
  admin.resources :projects do |project|
    project.resources :products, :member => { :new_action => :get }
  end
end
Simone Carletti
Thank you. Your solution was what I needed.
Radu
So you can accept it by flagging the green tick :)
Simone Carletti