Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add extra parameter to resources in routes

I want member routes generating by resources to contain additional parameter.

Something like:

resources :users

with folowing routes:

users/:id/:another_param
users/:id/:another_param/edit

Any ideas ?

like image 771
chumakoff Avatar asked Dec 04 '13 19:12

chumakoff


2 Answers

resources method doesn't allow to do that. But we can do something similar using the path option including extra parameters:

resources :users, path: "users/:another_param" 

This will generate urls like this:

users/:another_param/:id
users/:another_param/:id/edit 

In this case we will need to send :another_param value to routing helpers manually:

edit_user_path(@user, another_param: "another_value")
# => "/users/another_value/#{@user.id}/edit"

Passing :another_param value is not required if a default value has been set:

resources :users, path: "users/:another_param", defaults: {another_param: "default_value"}

edit_user_path(@user) # => "/users/default_value/#{@user.id}/edit"

Or we can even make the extra parameter not necessary in the path:

resources :users, path: "users/(:another_param)"

edit_user_path(@user) # => "/users/#{@user.id}/edit"

edit_user_path(@user, another_param: "another_value")
# => "/users/another_value/#{@user.id}/edit"

# The same can be achieved by setting default value as empty string:
resources :users, path: "users/:another_param", defaults: {another_param: ""}

If we need extra parameters for only certain actions, it can be done like this:

 resources :users, only: [:index, :new, :create]
 # adding extra parameter for member actions only
 resources :users, path: "users/:another_param/", only: [:show, :edit, :update, :destroy]
like image 63
chumakoff Avatar answered Oct 22 '22 00:10

chumakoff


you could do something more explicit like

 get 'my_controller/my_action/:params_01/:params_02', :controller => 'my_controller', :action => 'my_action'
like image 27
rav Avatar answered Oct 21 '22 23:10

rav