All threads / Routing question: Pass a 2nd parameter in the URL?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Routing question: Pass a 2nd parameter in the URL?

Alan Reid asked in Rails

Hi again :)
I would like to know how to get my routes how i want them haha as we all do :) Basically i want to get the edit variant URL to be like /products/:product_id/variants/:variant_id

instead of /products/:product_id/variants/edit

I have used the code below to get my routes, however its not doing what i thought it might.

# Products routing
resources :products do
  resource :variants, module: :products
end

This gives me the following routes...

product_variants        POST   /products/:product_id/variants(.:format)      products/variants#create
new_product_variants    GET    /products/:product_id/variants/new(.:format)  products/variants#new
edit_product_variants   GET    /products/:product_id/variants/edit(.:format) products/variants#edit
                        GET    /products/:product_id/variants(.:format)      products/variants#show
                        PATCH  /products/:product_id/variants(.:format)      products/variants#update
                        PUT    /products/:product_id/variants(.:format)      products/variants#update
                        DELETE /products/:product_id/variants(.:format)      products/variants#destroy

I believe you just want to use a plural resources on variants like so:

resources :products do
  resources :variants, module: :products
end

That will give you the urls for the individual nested objects so you can access and edit each of those separately.

Chris, can I just have a direct link to your brain, please? haha

Haha! Doing my best to make GoRails do that. 😉 The trick is when you've made as many mistakes coding as I have over the years...eventually you know where to look really fast to fix things.

Yeah haha I am getting there, can't believe how far i have come! Not to mention how i understand Rails better in 6 months compared to 8 years coding .NET!

You're making super good progress. And I know right? I started with GW-Basic, VB6, some C++, Java, back in my early days and it wasn't till I found Python that I felt like I could actually be productive and build full applications myself. Rails sped that up even quicker!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 35,699+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.