Tom Rossi
Tom Rossi

Reputation: 12066

How do I have route helpers use existing params?

Sometimes I won't have to provide a param to a route helper and it automagically pulls it in from the existing params. I can't seem to figure out how to get it to consistently work.

routes.rb:

  scope ':admin_id', module: :admin do
    resources :roles
  end

When rendering a page where the :admin_id is set to 10:

<%= roles_path %>                             # /10/roles
<%= edit_role_path(my_role, admin_id: 10) %>  # /10/roles/15/edit
<%= edit_role_path(my_role) %>                # sometimes works

rails routes:

     roles GET      /:admin_id/roles(.:format)                                                                roles#index
           POST     /:admin_id/roles(.:format)                                                                roles#create
  new_role GET      /:admin_id/roles/new(.:format)                                                            roles#new
 edit_role GET      /:admin_id/roles/:id/edit(.:format)                                                       roles#edit
      role GET      /:admin_id/roles/:id(.:format)                                                            roles#show
           PATCH    /:admin_id/roles/:id(.:format)                                                            roles#update
           PUT      /:admin_id/roles/:id(.:format)                                                            roles#update
           DELETE   /:admin_id/roles/:id(.:format)                                                            roles#destroy

Upvotes: 0

Views: 67

Answers (1)

Tom Rossi
Tom Rossi

Reputation: 12066

Figured it out!

def default_url_options(options={})
  { admin_id: params[:admin_id] }
end

This will add the param to all of my route helper methods so I don't have to specify it each time.

Upvotes: 1

Related Questions