jktress
jktress

Reputation: 1097

How do I enter race results in my app?

I have three models in my app: Athletes, Races, and Results. An Athlete has many results, a Race has many results, and a Result belongs to an Athlete and a Race. Each race has exactly 12 results.

As a beginning Rails developer, I'm having trouble understanding how to create the web form for entering the 12 race results. Should I maintain Results as a separate resource, or nest them under Races? In my controller, would I create 12 instances of a result object under the New action? How do I submit the appropriate race_id for each instance?

If you could help me clarify my thinking on this problem, and point me in the right direction, it would be greatly appreciated!

Upvotes: 0

Views: 58

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34350

You don't need to nest your results if they have unique and auto-generated IDs, but you can if you think it makes you application easier to use or program.

Your web form should probably be based on the use case of entering 12 athletes as they ranked for a single race. That means you could use multiple HTML inputs for each of the results:

<input type="hidden" name="race[results_attributes][][rank]" value="1" />
<input type="text" name="race[results_attributes][][athlete_id]" />
<input type="hidden" name="race[results_attributes][][rank]" value="2" />
<input type="text" name="race[results_attributes][][athlete_id]" />

You could then modify your race model to accept inputs for results:

class Race
  has_many :results
  accepts_nested_attributes_for :results
end

And simply pass the attributes in an update statement:

Race.find(params[:id]).update_attributes params[:race]

Upvotes: 1

Samo
Samo

Reputation: 8240

I'm sure there are several ways to approach this. You certainly could nest Results under Races, but then it becomes a question of whether you're creating the Results at the same time as their Race or not (this is worth thinking about because you need to know how to tie your Results to your Race, e.g. does each Result form have a race_id as a hidden field? If so the Race probably needs to already exist). But in either case this would probably be 12 Result forms with Result.new as the object.

Upvotes: 0

Related Questions