Rails: how can I nest only associated resources?
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 l开发者_运维技巧ists all players, not just those that belong to team 1.
How can I list only the resources that are associated with the parent resource?
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.
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.
精彩评论