trai bui
trai bui

Reputation: 598

How to create routes path into resource in rails 3

I understand resource and path routes in rails 3 but I do not know is there any way to have both routes ? I try this routes but it not work for me, this is the routes:

resources :roles, only: [:index, :create, :show, :update]
 get '/roles/:id' => 'roles#available_users'

How can we routes to use both routes ?

thankyou very much

Upvotes: 1

Views: 67

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Routes

What you're asking for cannot be done, as you'll be using the same "route" for different controller actions:

#config/routes.rb
resources :roles, only: [:index, :create, :show, :update] #-> domain.com/roles/:id - roles#show

If you then create another route for domain.com/roles/:id, Rails will just take the first which it finds in the routes file

--

The way to fix your issue is likely to be down to the following:

#config/routes.rb
resources :roles, except: [:edit, :destroy] do
   get :available_users # -> domain.com/roles/:id/available_users
end

This will take you to the roles#available_users action, providing you with the ability to load the view you wish (to display the users for a particular role)

For a more defined explanation, I'd recommend checking out the nested_resources part of the Rails routing system

Upvotes: 1

tomr
tomr

Reputation: 1134

If I understand you correctly you want something like this:

resources :roles, only: [:index, :create, :update] do
  get '/roles/:id' => 'roles#available_users'
end

Correct? Just add an "do" behind the closing ] and an end after the custom routes.

Edit: Apparently I got wrong. ;) What you could do is:

resources :roles, only: [:index, :create, :show, :update] do
  get '/roles/:id/available' => 'roles#available_users'
end

Upvotes: 0

Related Questions