Show action for nested resources

Hi I have a nested resource as shown below:

resources :decks do
    resources :cards, :except => "index"
end

this is my Decks controller

class DecksController < ApplicationController

  def index
    @decks = Deck.all
  end

  def show
    @deck = Deck.find(params[:id])
    @cards = @deck.cards
  end

  def new
   @deck = Deck.new
  end

  def create
    @deck = Deck.new(params[:deck])
    @deck.save
    redirect_to decks_path
  end

  def edit
    @deck = Deck.find(params[:id])
  end

  def update
    @deck = Deck.find(params[:id])
    @deck.update_attributes(params[:deck])
    @deck.save
    redirect_to deck_path(@deck)
  end

  def destroy
    @deck = Deck.find(params[:id])
    @deck.destroy
    redirect_to decks_path
  end

end

And this is the Cards controller show method which i want to show the back of the cards.

 class CardsController < ApplicationController

  def show
    deck = Deck.find(params[:id])
    @cards = deck.cards

  end

 end

Im stuck on what i need to to do get them to show.

Thanks

Hi Scott,

If you run rake routes and have a look at the route for cards#show you’ll see something like this:

deck_card GET    /decks/:deck_id/cards/:id(.:format)    cards#show

Notice the names of the parameters:

  • The ID of the Deck is passed in as params[:deck_id]
  • The ID of the Card is passed in as params[:id] (since this is the CardsController it makes sense that id should refer to a Card not a Deck)

It looks like you’re tying to look up a Deck using the ID of a Card.

Hope that helps,
George

1 Like