I am stuck on a problem which I just can't get a good solution to, and hope someone with more experience than me can help.
I'm creating a rails app where you can register matches in a game, and you pick which players were participants in that match by selecting from drop down lists. I am doing this by using form_for with nested fields_for.
<%= form_for [@group, @match] do |f| %>
<table class="table" id="match_players">
<tr>
<th>Placement</th>
<th>Player</th>
</tr>
<%= create_player_in_match_row(f, 1, @group.active_players) %>
<%= create_player_in_match_row(f, 2, @group.active_players) %>
</table>
<a id="add_player_row">Add Player</a>
<%= f.submit("Create") %>
<% end %>
The create_player_in_match_row method is for creating a row with a dropdown. The code is in a helper class and it looks like this:
def create_player_in_match_row(form, nr, players)
form.fields_for :player_in_matches, @match.player_in_matches.build do |pim|
"<tr id='row_p#{ nr }'>
#{ pim.hidden_field "placement", value: nr }
<td>#{ nr }.</td>
<td>#{ player_select_tag(pim, players) }</td>
<td>#{ tie_check_box(pim) }</td>
</tr>".html_safe
end
end
def player_select_tag(pim, players)
players = players.order "name ASC"
pim.select :player_id,
players.map { |p| [p.name, p.id] },
{ include_blank: false },
{ class: 'chosen-select' }
end
The problem: As you can see in the form_for I've got a link "Add Player". I want this button to add a new row with a dropdown for choosing players.
As of now I am creating a new row in coffeescript with something like this:
$("#add_player_row").click ->
select_row_original = document.getElementById('row_p1')
new_select_row = select_row_original.cloneNode(true)
new_select_row_placement = document.getElementsByClassName('player_row').length + 1
# Change A LOT of ids and stuff
$("#match_players").append(new_select_row)
But this feels hacky and has really unintuitive code. Can someone point me in the direction of a smarter solution? Is there some way I can reuse the helper class method for adding row?