【问题标题】:Conditionally calling 'collection_select' from a model/helper with AJAX使用 AJAX 从模型/助手有条件地调用“collection_select”
【发布时间】:2013-10-24 08:20:49
【问题描述】:

我正在循环遍历已构建的 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) %>");

【问题讨论】:

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


    【解决方案1】:

    您可以在模型中调用助手:

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

    因此,据我所知,您应该将team_or_player() 更改为类方法并使用以下方法调用它:

    Standings.team_or_player(@standing, @game)
    

    或作为实例

    @standing.team_or_player(@standing, @game)
    

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

    我的偏好是将逻辑直接放在视图中或提供给助手。

    【讨论】:

    • 我最终把它放在 application_helper 中 - 但ActionController::Base.helpers.collection_select() 很有用,即使它对我来说应该是显而易见的:p +1 谢谢!
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多