如何在simple_form中使用select2-rails?

时间:2013-02-28 21:47:10

标签: ruby-on-rails ruby-on-rails-3 simple-form jquery-select2 select2-rails

This select2 jquery库看起来很棒。有一个Rails gem,但文档上的内容非常清晰。 我想使用自动完成功能生成一个简单的多下拉菜单。我该怎么做?

这是我的simple_form_for电话:

<%= f.input_field :neighborhood_names, url: autocomplete_neighborhood_name_searches_path, as: :autocomplete, data: { delimiter: ',', placeholder: "Where do you want to live?"}, multiple: true, id: "selectWhereToLive", class: "span8" %>

我已经成功安装了select2-rails gem,但不太确定如何让它正常工作。

我将其添加到我的home.js.coffee文件中:

jQuery ->
    $('#selectWhereToLive').select2()

我收到此错误:

Uncaught query function not defined for Select2 selectWhereToLive 

思想?

修改1:

以上simple_form_for调用正在生成此HTML:

<input class="autocomplete optional span8" data-autocomplete="/searches/autocomplete_neighborhood_name" data-delimiter="," data-placeholder="Where do you want to live?" id="selectWhereToLive" multiple="multiple" name="search[neighborhood_names][]" size="30" type="text" url="/searches/autocomplete_neighborhood_name" value="" />

表示正确设置了id属性。

修改2 - 更新

正如@moonfly建议的那样,我尝试将as: :select添加到f.input_field - 两者都包含as: :autocomplete而不包括在内。

没有as: :autocomplete的结果HTML就是:

<input name="search[neighborhood_names][]" type="hidden" value="" /><select class="select optional span8" data-delimiter="," data-placeholder="Where do you want to live?" id="selectWhereToLive" multiple="multiple" name="search[neighborhood_names][]" url="/searches/autocomplete_neighborhood_name"><option value="true">Yes</option>
<option value="false">No</option></select>

预先填充2个选项值“是”和“否”。不太清楚为什么,但这就是它的作用。

更新

所以我更改了jquery选择器以查找input#ID,并忘记了。所以我把它设置回来,现在它正在生成选择框 - 但它给了我那些2是&amp;没有选择。不太清楚为什么会这样做。它没有从我的url属性中返回值。

编辑3

@ harish-shetty的建议似乎有效。但是现在,在通过自动完成并使用select2菜单成功找到记录之后,它绕过了我在search.rb模型上的setter方法。

基本上,我想要发生的是,一旦用户填写完表单 - 并且我拥有他们想要的社区的所有ID /名称,我想在search_neighborhoods中创建一个新记录那些ID。

所以这些是我的方法:

Search.rb

  def neighborhood_names
    neighborhoods.map(&:name).join(',')
  end

  # we need to put [0] because it returns an array with a single element containing
  # the string of comma separated neighborhoods
  def neighborhood_names=(names)
    names[0].split(',').each do |name|
      next if name.blank?
      if neighborhood = Neighborhood.find_by_name(name)
        search_neighborhoods.build neighborhood_id: neighborhood.id
      end
    end
  end

我的SearchController.rb

  def autocomplete_neighborhood_name
    @neighborhood = Neighborhood.select("id, name").where("name LIKE ?", "#{params[:name]}%").order(:name).limit(10)

    respond_to do |format|
      format.json { render json: @neighborhood , :only => [:id, :name] }
    end    
  end

这就是请求现在的样子 - 这表明没有创建search_neighborhood条记录:

Started POST "/searches" for 127.0.0.1 at 2013-03-06 04:09:55 -0500
Processing by SearchesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"7SeA=", "search"=>{"boro_id"=>"", "neighborhood_names"=>"1416,1394", "property_type_id"=>"", "min_price"=>"", "max_price"=>"", "num_bedrooms"=>"", "num_bathrooms"=>""}}
  Neighborhood Load (0.5ms)  SELECT "neighborhoods".* FROM "neighborhoods" WHERE "neighborhoods"."name" = '1' LIMIT 1
   (0.3ms)  BEGIN
  SQL (0.8ms)  INSERT INTO "searches" ("amenity_id", "boro_id", "created_at", "keywords", "listing_type_id", "max_price", "min_price", "neighborhood_id", "num_bathrooms", "num_bedrooms", "property_type_id", "square_footage", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING "id"  [["amenity_id", nil], ["boro_id", nil], ["created_at", Wed, 06 Mar 2013 09:09:55 UTC +00:00], ["keywords", nil], ["listing_type_id", nil], ["max_price", nil], ["min_price", nil], ["neighborhood_id", nil], ["num_bathrooms", nil], ["num_bedrooms", nil], ["property_type_id", nil], ["square_footage", nil], ["updated_at", Wed, 06 Mar 2013 09:09:55 UTC +00:00]]
   (32.2ms)  COMMIT
Redirected to http://localhost:3000/searches/29

3 个答案:

答案 0 :(得分:24)

select2插件支持自动完成。您可以按如下方式使用本机自动完成:

<%= f.input_field :ac_neighborhood_ids, 
      data: { 
        placeholder: "Where do you want to live?",
        saved: @search.neighborhoods.to_json,
        url: autocomplete_neighborhood_name_searches_path
      }, 
      input_html:  { class: "span8 ac-select2" }
%>

Javscript

$(document).ready(function() {  
  $('.ac-select2').each(function() {
    var url = $(this).data('url'); 
    var placeholder = $(this).data('placeholder'); 
    var saved = jQuery.parseJSON($(this).data('saved'));
    $(this).select2({
      minimumInputLength: 2,
      multiple: true,
      placeholder : placeholder,
      allowClear: true,
      ajax: {
        url: url,
        dataType: 'json',
        quietMillis: 500,
        data: function (term) {
          return {
            name: term
          };
        },
        results: function (data) {
          return {results: data};
        }
      },

      formatResult: function (item, page) {
        return item.name; 
      },

      formatSelection: function (item, page) {
        return item.name; 
      },

      initSelection : function (element, callback) {
        if (saved) {
          callback(saved);
        }
      }

    });
  });
});

确保autocomplete_neighborhood_name_searches_path处的操作返回一个json哈希数组。每个哈希应包含idname字段。自动完成的术语通过查询参数name传递。

  def autocomplete_neighborhood_name
    @neighborhood = Neighborhood.select("id, name").where("name LIKE ?", "#{params[:name]}%").order(:name).limit(10)

    respond_to do |format|
      format.json { render json: @neighborhood , :only => [:id, :name] }
    end    
  end

您的搜索模型:

class Search

  attr_accessor :ac_neighborhood_ids

  has_many :search_neighborhoods
  has_many :neighborhoods, through: :search_neighborhoods

  def ac_neighborhood_ids
    neighborhood_ids.join(",")
  end

  def ac_neighborhoods
    neighborhoods.map{|n| {:id => n.id, :name => n.name}}
  end

  def ac_neighborhood_ids=(ids)
    search_neighborhoods.clear # remove the old values
    ids.split(',').select(&:present?).map do |neighborhood_id|
      search_neighborhoods.build neighborhood_id: neighborhood_id
    end
  end

end    

答案 1 :(得分:1)

我相信您需要选择选择标签(然后从中读取数据)或输入隐藏标签,然后您需要提供'查询'功能。在您的情况下,它附加到输入标记,从而查找查询函数。尝试在as: :select来电时设置f.input_field

答案 2 :(得分:0)

用作:: select with collection是select2的常规方法。 在select2上绑定自动完成是一个javascript问题。

这是我的代码示例。但没有自动完成功能。 https://gist.github.com/kuboon/f692d9a844c0ff5877c8