简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM