1

I have a simple application in which the user can manage decks of cards.

In my model I have:

  • Card
  • DeckOfCards

In my view /DeckOfCards/:id/edit

I want to allow the user to create a new card and add it to the current deck.

I currently have a form_for helper that posts to to /Cards/new

Should my Cards controller be hard coded to redirect back to DeckOfCards? What if later I want to create cards independently of a deck?

Another possible approach I am considering is a custom action on my DeckOfCards controller to handle this case. If I do that is there a way to use form helpers or does that require I post back to the associated controller for the object I am creating?

I am liking the structure that rails brings but when dealing with multiple entities it is not clear in my mind what the architecture should look like. I fear if I misuse these paradigms I will end up in a world of pain!

Can you recommend a more flexible way to approach this?

Thanks for any help

emrass
  • 6,253
  • 3
  • 35
  • 57
Chris
  • 6,076
  • 11
  • 48
  • 62

1 Answers1

3

The setup should be quite simple:

You said you have two models: Cards and DeckOfCards. Perfect!

Now in your routes:

resources :cards
resources :deckofcards do
  resources :cards, :controller => "cardsindeck" # gives you, e.g. <root>/deckofcards/1/cards/5/show
end

Now you need two distinct controllers for cards:


CardsController: handles CRUD for cards independent from DeckOfCards (you can still have links there to the DeckOfCards a card belongs to)

CardsInDeckController: handles cards through DeckOfCard's


In the CardsInDeckController, you can access the DeckOfCards the current card belongs to by params[:deckofcards_id], e.g. in your new action:

@card = DeckOfCards.find(params[:deckofcards_id]).cards.build
emrass
  • 6,253
  • 3
  • 35
  • 57
  • 2
    This looks good. Note that blackbird07 has routes for cards both on their own and within the context of a deck of cards. This is good! What this open up is that you will have the ability to edit an individual card as you specified in your requirements and also to edit a card within the context of a desk. The nesting for that will greatly help in giving you the route3s you can then use. Try 'rake routes' to see all the path helpers that you will have available. – Michael Durrant Nov 22 '11 at 14:29
  • 1
    n.b. although we are taking about 'route nesting' you can also utilize form row details (e.g. cards for a given desk) using forms with models that have `accepts_nested_attributes_for` with other models – Michael Durrant Nov 22 '11 at 14:31
  • 1
    Thanks a lot for elaborating on the solution, @MichaelDurrant This definitely helps! – emrass Nov 22 '11 at 14:39
  • Thanks a lot to everyone, this has given me a lot of ideas to play with. – Chris Nov 22 '11 at 15:29