I’m trying to add guessing functionality to the Flashcards App.
The way i see it, a guess is taken on a particular card, so a guess belongs_to a card, and a card has_many guesses. So far so good, but when it comes to routing i’ve read that Resources should never be nested more than 1 level deep and that a way to avoid deep nesting is using shallow nesting, i.e. only generate collection actions scoped under the parent.
So now i have the following in my routes.rb file
resources :decks do resources :cards, except: :index do resources :guesses, only: [:new, :create] end end resources :guesses, only: :show
and my GuessesController looks like this:
class GuessesController < ApplicationController before_filter :authenticate def show @guess = find_guess unless @guess.belongs_to_user? current_user redirect_to decks_path end @card = @guess.card @deck = @card.deck end def new @deck = find_deck @card = find_card @guess = @card.guesses.new end def create @deck = find_deck @card = find_card @guess = @card.guesses.new(params[:guess]) @guess.save redirect_to @guess end def find_deck current_user.decks.find(params[:deck_id]) end def find_card @deck.cards.find(params[:card_id]) end def find_guess guess = Guess.find(params[:id]) end end
Which seems to work fine, but since the show action is not being accessed through deck and card (route is simply /guesses/:id) i have to check to make sure that the user isn’t trying to access guesses that don’t belong to him.
My question is, am i going about this the right way? Is there a better approach? Should i simply deep nest my routes?
Thanks in advance