使用AJAX从模型/帮助器中有条件地调用'collection_select'

时间:2013-10-24 08:20:49

标签: ruby-on-rails ajax ruby-on-rails-3

我循环遍历构建的sub-tournament的每个实例 - 而我遇到的问题与通过ajax获取的数据有条件地创建collection_select框有关。这是视图 - 我要插入代码的行标记为:

查看

<% @tournament.sub_tournaments.each_with_index do |sub, i| %>
  <%= f.fields_for :sub_tournaments, sub, :validate => false do |sub_form| %>
    <div class="tab-content standings-row-<%= i %>" style="display:none">
      <table>
        <thead>
          <tr>
            <th> <h4>Standing</h4> </th>
            <th class="standings-field-<%= i %>"></th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <%= sub_form.fields_for :standings, :validate => false do |standings| %>
            <tr>
              <td>
                <%= f.hidden_field :_destroy %><%= f.text_field :standing, :class => "standing", readonly: true, :type => "" %>
              </td>
              <td class="standings-ajax-<%= i %>">**INSERT HERE**</td>
              <td><span class="remove">Remove</span></td>
            </tr>
          <% end %>  
        </tbody>
      </table>
      <div class="add-item">
        <%= link_to_add_standings_fields(sub_form, :standings) %>
      </div>
    </div>
  <% end %>
<% end %>  

我想在控制器中进行条件检查(取决于所选择的游戏是团队游戏还是单人游戏),但它似乎更有意义作为方法(或帮助者?)。目前我已经在Standing.rb(下方)中了解了 - 但我得到了no method "collection_select"错误 - 因此可能在模型中无法形成帮助程序,这似乎是合理的。那怎么能这样呢?

Standing.rb

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

我怎样才能将f传递给我的AJAX电话?

AJAX

$(".standings-ajax-<%= @tab_number %>").html("<%= ** ?? **.team_or_player(@standing, @game) %>");

1 个答案:

答案 0 :(得分:1)

您可以在模型中调用帮助程序:

ActionController::Base.helpers.collection_select( ... )

因此,我可以看到您应该将team_or_player()更改为类方法并将其命名为:

Standings.team_or_player(@standing, @game)

或作为实例

@standing.team_or_player(@standing, @game)

但您应该使用self而不是传递@standing

我倾向于将该逻辑直接放在视图中或帮助。