Rails 3 Routing Error with Nested Resources

2019-09-03 08:22发布

问题:

In my Rails application, there are many games, and each game has it's own set of leaderboards. It makes sense then, to have the leaderboards nested in the game, so you can only get to a leaderboard through a game. I setup my routes.rb file as such (the important part):

resources :games do
  resources :leaderboards
end

So then I updated my controller so it would get the appropriate game from the game_id passed in, and grab the leaderboard information from that. However, my issues comes from my view. In this section (auto generated view from the scaffold):

<% @leaderboards.each do |leaderboard| %>
  <tr>
    <td><%= leaderboard.name %></td>
    <td><%= leaderboard.scoreColumnName %></td>
    <td><%= leaderboard.game_id %></td>
    <td><%= link_to 'Show', [@game, leaderboard] %></td>
    <td><%= link_to 'Edit', edit_game_leaderboard_path(leaderboard) %></td>
    <td><%= link_to 'Destroy', [@game, leaderboard], :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

The code breaks saying:

No route matches {:action=>"edit", :controller=>"leaderboards", :game_id=>#<Leaderboard id: 1, name: "Test High Score Leaderboard", scoreColumnName: "Score", game_id: 1, created_at: "2011-07-03 01:32:33", updated_at: "2011-07-03 01:32:33">}

This line, it turns out is the error: (line 19 in my code)

<td><%= link_to 'Edit', edit_game_leaderboard_path(leaderboard) %></td>

Removing this line, and the view renders fine. So, the URL part is broken, but how do I fix it? The weird thing is, I have that exact "edit_game_leaderboard_path" in the Show view, and it works fine... what am I doing wrong?

回答1:

You want:

<%= link_to 'Edit', edit_game_leaderboard_path(@game, leaderboard) %>