views:

19

answers:

2

To set up nested resources in Rails, I have seen example routes given like this:

map.resources :players
map.resources :teams, :has_many => :players

By doing this, you can visit teams/1/players and see a list. But it lists all players, not just those that belong to team 1.

How can I list only the resources that are associated with the parent resource?

A: 

The problem has little to do with map.resources and routing in general.

Note, players are not fetched magically by the framework: there's some action in some controller processing teams/1/players request and your code there fetches list of players to show. Examining that action (or posting here) should help.

Nikita Rybak
+3  A: 

You need to load the team first. A common practice is to do this in a before filter.

class PlayersController < ActionController::Base
  before_filter :get_team

  def get_team
    @team = Team.find(params[:team_id])
  end

  def index
    @players = @team.players # add pagination, etc., if necessary
  end

  def show
    @player = @team.players.find(params[:id])
  end
end

Note that the code above insists that you specify a team. If you want the same controller to work for both, you need to change it slightly (i.e. check for params[:team_id]).

You can use the excellent inherited_resources gem to DRY this up if you controller logic is straightforward.

Dave Pirotte