One Submit button with multiple forms
I'm trying to create a scoring App. Since I'm new to StackOverflow I can't upload the screen shots but here are screen shot links
- Now it looks like this.
- This is what I want it to be.
- Here are the models involve in the view. Just click the next picture = the last picture in the Photostream (again StackOverflow won't allow me to post more than 3 hyperlinks).
This view above is from: localhost/matchdays/4/matches/new
The relationship would look like this:
- A Matchday has_many matches.
- A Match has_many games (maximum of 3, but for now we'll stick with 1). We will update the score attribute.
- A Game has_many pairs (maximum 2).
My question is:
How do you code in the MatchesController (when the user hit Start) to create a game with 2 pairs and each pair has its own score (which is an attribute in the Game model)?
How do you loop in the view to add another Game(Score attribute) and Pair form that belongs to the Match (in this case Match 10)? Just like in the screen shot 2 above.
Matches Controller:
def new
@matchday = Matchday.last
@match = Match.new()
@match.number = match_numbering
@pairs = Pair.all
@matchday.best_of.times { @match.games.build }
end
def create
@match = Match.new(params[:match])
@matchday = Matchday.last
@match.number = match_numbering
if @match.save
@matchday.matches << @match
flash[:success] = "Match recorded"
开发者_如何学Python redirect_to matchdays_path
else
@title = "Record Match"
render 'new'
end
end
/views/matches/new:
<h1>Match <%= @match.number %> of Matchday <%= @matchday.number %> details</h1>
<%= form_for @match, :url => {:action => 'create', :id => @match.id } do |p| %>
<%= render 'shared/error_messages', :object => p.object %>
<%= render :partial => 'match_form', :locals => {:p => p} %>
<% for game in @match.games %>
<%= fields_for :games, game do |game_form| %>
<p>
Score: <%= game_form.text_field :score, :size => 2 %>
</p>
<p>
Pair: <%= select(@pairs, :pair_id,Pair.all.collect{|p| [p.name]}) %>
</p>
<% end %>
<% end %>
<div class = "action_links">
<p> <%= link_to "Cancel", matchdays_path, :class => "cancel" %> |
<%= p.submit "Start" %></p>
</div>
<% end %>
I think the looping must be put some where in the for loop, but not sure how to implement it. Plus my fields_for and select form might might not be correct... much to learn :)
All I had to do was add this line to the Match.rb
has_many :games
accepts_nested_attributes_for :games, :allow_destroy => true
精彩评论