chumakoff
chumakoff

Reputation: 7034

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 ?

Upvotes: 11

Views: 17087

Answers (3)

chumakoff
chumakoff

Reputation: 7034

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

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

That will generate urls like this:

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

In this case you 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 you can even make the extra parameter not mandatory 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 you need extra parameters for particular actions, it can be done this way:

 resources :users, only: [:index, :new, :create]
 # adding extra parameter for member actions only
 resources :users, path: "users/:another_param/", only: [:show, :edit, :update, :destroy]
  

Upvotes: 21

NARKOZ
NARKOZ

Reputation: 27911

resources :users, path: 'user' do
  collection do
    get ':id/:some_param', action: :action_name 
    get ':id/:some_param/edit', action: :custom_edit
  end
end

Upvotes: 2

rav
rav

Reputation: 753

you could do something more explicit like

 get 'my_controller/my_action/:params_01/:params_02', :controller => 'my_controller', :action => 'my_action'

Upvotes: 3

Related Questions