0

このサンプル ガイド ( http://rails-select2-example.herokuapp.com/ ) に従って、select2 ドロップダウンを作成し、データベースから国を検索しています。

ただし、選択ボックスは常に「結果が見つかりません」で空に戻ります。js/ajax から値を取得しないのはなぜですか?

見る (new.html.erb)

          <select class="form-control" id="country_select">
          </select>

コントローラー (Searches_controller.rb)

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def new
        @countries = Country.all
        respond_with @countries
    end
end

Javascript

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= user_searches_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });

ルート

resources :users do
    resources :searches
  end

移行する検索

class CreateSearches < ActiveRecord::Migration

  def change
      t.string :country
   end
      add_index :searches, [:user_id, :created_at]

  end
end
4

2 に答える 2

1

国で検索するには、AJAX を使用する代わりに、Rails Helper Method を直接使用できます。

以下の例を参照してください。

application_helper.rbファイルに 1 つのメソッドを作成します。

def get_country
  Country.pluck(:name,:id)
end

あなたのビューファイルで:

<%= f.select :country_select, get_country, {prompt: 'Select Country'} %>

最後に、次のように js コードを追加します。

$("#country_select").select2({
  placeholder: "Select Country"
});
于 2016-06-28T12:07:09.087 に答える
1

new actionでコードを書いているので、呼び出していた URL が間違っています. new action から呼び出したい場合は、

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def new
        @countries = Country.all
        respond_with @countries
    end
end

このように ajax 呼び出しで URL を変更するか、

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= new_user_search_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });

または、コードを index アクションに変更し、

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def index
        @countries = Country.all
        respond_with @countries
    end
end

次に、そのURLを使用できます。

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= user_searches_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });
于 2016-06-28T12:32:28.263 に答える