Dominic Sayers
Dominic Sayers

Reputation: 1793

Rails app has parent & child ids wrong way round in route helper

I have an Rails app with a parent object Mom and child object Kid. The scaffolds were as far as possible generated rather than hand-coded. In /app/views/kids/_kid.html.erb I added

<%= mom_kid_path(kid) %>

For a Mom with id 1 and a Kid with id 2 this is showing /moms/2/kids/1, which has the ids the wrong way round.

All I have in /config/routes.rb is

resources :moms do
  resources :kids
end

What did I do wrong?

The code for the app is at https://github.com/dominicsayers/momkid. The exact steps I took to create the app are here: https://www.dominicsayers.com/howto-create-a-simple-parent-child-form-in-rails-3-1/. I'm happy to add any other specific information that is requested.

Upvotes: 2

Views: 500

Answers (1)

Msencenb
Msencenb

Reputation: 5104

EDIT/ANSWER:

Rails needs both the mom and kid variable when using the _path helper. So it should look more like this:

<%= mom_kid_path(kid.mom, kid) %>

Original answer... misunderstood the question a bit but it has a helpful link:

This is the default behavior for rails, it is not backwards.

You're nested route basically reads, "Each resource mom has a set of sub/nested resources named kids".

This page is a great resource.. I've linked to the nested routes section so maybe it can help clear this issue up for you. Rails Routing

Upvotes: 7

Related Questions