Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resource routes to be mapped to a custom path in rails 4

I have a route like:

resources :products

Now I have all my code is in place but just need to change the paths from /products/:action to /items/:action

I have already skimmed through the rails docs but could not figure this out. It looks very basic and should be easy, but I just cant put my finger on it.

The url I used was: http://guides.rubyonrails.org/routing.html#path-and-url-helpers

like image 624
whizcreed Avatar asked Feb 18 '15 10:02

whizcreed


People also ask

What are resources in Rails routes?

2.1 Resources on the Web Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET , POST , PATCH , PUT , and DELETE . Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

How do I find routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.


2 Answers

You can write your route like this:

resources :products, path: 'items'

This will generate /items routes with product_* named helpers, using ProductsController. Have a look at this part of the Routing Guides.

like image 55
dgilperez Avatar answered Sep 21 '22 18:09

dgilperez


There are several ways you can accomplish this. One is to simply name your resource items and specify the controller with the :controller option.

resources :items, controller: 'products'

This will recognize incoming paths beginning with /items but route to the ProductsController. It will also generate route helpers based on the resource name (e.g. items_path and new_item_path).

Another way is to use the :path option when specifying the resource as pointed out by @dgiperez.

resources :products, path: 'items'

This will also route paths beginning with /items to the ProductsController but since the route helpers are based on the resource name, they would be based on products (e.g. products_path and new_product_path)

Reference

like image 32
Bart Jedrocha Avatar answered Sep 18 '22 18:09

Bart Jedrocha