我正在尝试创建一个得分应用程序。由于我是StackOverflow的新手,我无法上传屏幕截图,但这里是屏幕截图链接
以上观点来自:localhost / matchdays / 4 / matches / new
这种关系看起来像这样:
我的问题是:
你如何在MatchesController中编码(当用户点击Start时)创建一对2对游戏,每对都有自己的分数(这是游戏模型中的属性)?
< / LI>如何在视图中循环添加另一个Game(Score属性)和属于Match的Pair表单(在本例中为Match 10)?就像在上面的屏幕截图2中一样。
匹配控制器:
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"
redirect_to matchdays_path
else
@title = "Record Match"
render 'new'
end
end
/视图/匹配/新:
<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 %>
我认为循环必须放在for循环中的某些位置,但不确定如何实现它。另外,我的fields_for和select表单可能不正确...很多东西要学习:)
答案 0 :(得分:0)
我所要做的就是将此行添加到Match.rb
has_many :games
accepts_nested_attributes_for :games, :allow_destroy => true