user281104
user281104

Reputation:

How to add a new action in Ruby on Rails?

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.

Upvotes: 0

Views: 471

Answers (3)

Simone Carletti
Simone Carletti

Reputation: 176352

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

Upvotes: 1

Vitaly Kushner
Vitaly Kushner

Reputation: 9455

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

Upvotes: 1

klew
klew

Reputation: 14967

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.

Upvotes: 0

Related Questions