我有以下型號我使用...如何設置一個用於在Rails中添加關聯記錄的靜態表單?
遊戲
class Game < ActiveRecord::Base
has_many :workout
has_many :participations
end
參與
class Participation < ActiveRecord::Base
belongs_to :player
belongs_to :game
end
鍛鍊
class Workout < ActiveRecord::Base
belongs_to :player
belongs_to :game
has_many :measurables
end
測
class Measurable < ActiveRecord::Base
belongs_to :workout
end
Workout
是目前Player
嵌套資源。通常,我會在Player
之間創建一個Workout
記錄。我還會使用寶石nested_fields_for將Measurable
添加到Workout
,但這樣可以讓我一次只能爲一個玩家添加/移除一次可測量的值。我正在嘗試爲用戶編寫一個表單,以便爲參與遊戲的每個玩家編輯多個測量值。
例表
Player | Height | Weight | Hand Span |
Player 1's Name [input box] [input box] [input box]
Player 2's Name [input box] [input box] [input box]
Player 3's Name [input box] [input box] [input box]
Player 4's Name [input box] [input box] [input box]
我到目前爲止建立了我的意見/遊戲edit_measurables.rb
目錄和games_controller
稱爲#edit_measurables的作用下視圖。我打算在這裏創建或查找對應於Game
的Workout
並構建上面顯示的表單。雖然我不確定該從哪裏出發。我認爲我的模特和協會有不正確的組織。
更新:
我已經成功地相處遠一點,但我仍然運行到的幾個問題,雖然一些這個問題的範圍之外。
我想構建我想通過以下方式來處理的形式...
<table>
<thead>
<tr>
<th>Player</th>
<th>Height</th>
<th>Weight</th>
<th>Hand</th>
</tr>
</thead>
<tbody>
<% @game.participations.each do |participant| %>
<% player = participant.player %>
<% simple_form_for participant.player do |player_form| %>
<% workout = Workout.find_or_create_by(...) %>
<% @measurables.each {|m| workout.measurables.build(...) unless workout.measurables.any? { ... } } %>
<tr>
<td><%= player.full_name %></td>
<% player_form.nested_fields_for :measurables, workout.measurables, wrapper_tag: :td do |measurable_form| %>
<td><%= measurable_form.input :value, label: false %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
有趣。你有沒有任何代碼?我有代碼可以給你你需要的東西,但是它不能添加動態值等。 –
'<%game.participations.each do | participation | %> <%鍛鍊= participation.game.workout%> <%=的form_for participation.player做| player_form | %> <%= fields_for player.measureables.where(鍛鍊:鍛鍊)do | measurable_form | %> <%= measurable_form.text_field:高度%> <% end %> <% end %> <% end %>'這將意味着我需要提交按鈕的每一行,雖然我認爲 - 這是不是我想要的.. – daveomcd
謝謝你,讓我寫一個答案。它可能不會是你所需要的,但可能會給出想法 –