Note that there are some explanatory texts on larger screens.

plurals
  1. POConditionally calling 'collection_select' from a model/helper with AJAX
    text
    copied!<p>I'm looping through each instance of a built <code>sub-tournament</code> - and the problem that I'm having has to do with conditionally creating a <code>collection_select</code> box with data fetched via ajax. Here's the view - the line I want to insert code in is marked:</p> <p><strong>View</strong></p> <pre><code>&lt;% @tournament.sub_tournaments.each_with_index do |sub, i| %&gt; &lt;%= f.fields_for :sub_tournaments, sub, :validate =&gt; false do |sub_form| %&gt; &lt;div class="tab-content standings-row-&lt;%= i %&gt;" style="display:none"&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; &lt;h4&gt;Standing&lt;/h4&gt; &lt;/th&gt; &lt;th class="standings-field-&lt;%= i %&gt;"&gt;&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;%= sub_form.fields_for :standings, :validate =&gt; false do |standings| %&gt; &lt;tr&gt; &lt;td&gt; &lt;%= f.hidden_field :_destroy %&gt;&lt;%= f.text_field :standing, :class =&gt; "standing", readonly: true, :type =&gt; "" %&gt; &lt;/td&gt; &lt;td class="standings-ajax-&lt;%= i %&gt;"&gt;**INSERT HERE**&lt;/td&gt; &lt;td&gt;&lt;span class="remove"&gt;Remove&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="add-item"&gt; &lt;%= link_to_add_standings_fields(sub_form, :standings) %&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>I thought about doing the conditional check (it depends upon whether the game selected is a team game or a single-player game) in the controller, but it seems to make more sense as a method (or a helper?). At the moment I have it in <code>Standing.rb</code> (below) - but I'm getting a <code>no method "collection_select"</code> error - so probably form helpers aren't available in models, which seems reasonable. So how could I do this? </p> <p><strong>Standing.rb</strong></p> <pre><code>def team_or_player(game) if Game::TEAM_GAMES.include?(game.name) self.collection_select(:team_division_id, TeamDivision.where("game_id = ?", game.id), :id, :name, {include_blank: true}) else self.collection_select(:player_id, Player.where("game_id = ?", game.id), :id, :handle, {include_blank: true}) end end </code></pre> <p>And how can I pass the <code>f</code> to my AJAX call? </p> <p><strong>AJAX</strong></p> <pre><code>$(".standings-ajax-&lt;%= @tab_number %&gt;").html("&lt;%= ** ?? **.team_or_player(@standing, @game) %&gt;"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload