Search code examples
ruby-on-railsrestroutesnested-routescustom-routes

Map one controller action on another action rails


I have a controller named carts_controller and in my routes I am using restful routes i.e., resources :carts.

I know resources create default actions like create, index etc., but if I don't want to user create and create a method add_to_cart and in routes I have defined its route as

post '/add_cart/:product_id/' => 'carts#add_to_cart', as: 'add_to_cart' 

Does this route considered RESTFUL?

I don't want to user all the default RESTFUL routes created by resources. I want some custom actions in place of these. My code is working but I am confused as my concepts are not clear. Another thing is if I know that I need product_id in my routes, should I make them nested inside products resources or it will work if I define custom ad I defined above?

Any help would be appreciated!


Solution

  • I think your current approach is fine. Not all controller actions will fit nicely into the standard CREATE/UPDATE/DESTROY actions. It's also pretty obvious what add_to_cart does.

    As an alternative you could consider doing this in the update action of the cart controller. If a cart has many products you could consider using nested params:

    params: {
      cart: {
        products_attributes: [{
          "0" => { ...product_attributes_here.. }
        },
        ...
      }
    }