【问题标题】:Ajax call on a <select> in a formtastic form以表单形式对 <select> 进行 Ajax 调用
【发布时间】:2017-01-17 15:04:38
【问题描述】:

我需要在我的应用程序中从提供者列表中选择一个提供者,然后通过 ajax,我可以在下面看到属于特定提供者的类别列表。我在 activeadmin 中有一个表单:

<%= semantic_form_for [:admin, @game], builder: ActiveAdmin::FormBuilder do |f| %>
  <%= f.semantic_errors :state %>
    <%= f.inputs do %>
        <%= f.input :categorization_id, label: 'Provider', as: :select,
                    collection: Provider.all.map { |provider| ["#{provider.name}", provider.id] },
                    input_html: { class: (:provider_select), 'data-url': category_select_path(provider: 4) } %>
        <%= f.input :categorization_id, label: 'Category',input_html: { class: ('category_dropdown') }, as: :select,
                    collection: Category.all.map { |category| ["#{category.name}", category.id]}%>
        ...

    <% end %>
  <%= f.actions %>
<% end %>

在 activeadmin 控制器中我有:

controller do
  def ajax_call
      @provider = Provider.find(params[:provider])
      @categories = @provider.categories
      respond_to do |format|
        format.json { render json: @categories }
      end
    end
end

JS:

$(document).on('ready page:load', function () {

  $('.select.input.optional').last().addClass('hidden_row');

  $('#game_categorization_id').change(function () {
    var id_value = this.value;
    $('.hidden_row').removeClass('hidden_row');
    $.ajax({
      type: 'GET',
      url: '/admin/games/category_select'
      // data: id_value
    })
  });

});

还有路线:match '/admin/games/category_select' =&gt; 'admin/games#ajax_call', via: :get, as: 'category_select'

我不知道,如何将提供者 ID 从集合传递到 url。目前,我有category_select_path(provider: 4),但实际上它必须是smth。像这样 - category_select_path(provider: provider.id) 在浏览器中,在 devtools 的 Network 选项卡中,我可以看到我的 category_select,但是有一个错误:Couldn't find Game with 'id'=category_select。我不知道它从哪里来。有什么建议么?谢谢。

【问题讨论】:

    标签: ruby-on-rails ajax activeadmin formtastic


    【解决方案1】:

    问题出在路由中:match '/admin/games/category_select' =&gt; 'admin/games#ajax_call', via: :get, as: 'category_select'。它由 Activeadmin 控制器的show 操作保留。所以我将路由更改为:get '/admin/select_category' =&gt; 'admin/games#get_providers_categories', as: 'select_category',并添加到ajax,调用data: {provider: provider},这样我就可以在提供者的参数id中触发:

    $.ajax({
          type: 'GET',
          url: '/admin/select_category',
          data: {
            provider: provider
          },
          success: (function (data) {
              $('#select_category').children('option').remove();
              $('#select_category').prepend('<option value=""></option>');
              $.each(data.categories, function () {
                $('#select_category').append('<option value="' + this.id + '">' + this.name + '</option>')
              })
          })
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      相关资源
      最近更新 更多