简体   繁体   English

如何在simple_form中使用select2-rails?

[英]How do I use select2-rails with simple_form?

This select2 jquery library looks awesome. 这个 select2 jquery库看起来很棒。 There is a Rails gem but it is very light on the documentation. 有一个Rails宝石,但它在文档上非常轻松。 I would like to generate a simple multiple drop-down menu, using autocomplete. 我想使用自动完成功能生成一个简单的多下拉菜单。 How do I do that? 我怎么做?

This is my simple_form_for call: 这是我的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" %>

I have successfully installed the select2-rails gem, but not quite sure how to get it working. 我已成功安装了select2-rails gem,但不太确定如何使其工作。

I add this to my home.js.coffee file: 我把它添加到我的home.js.coffee文件中:

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

And am getting this error: 我收到这个错误:

Uncaught query function not defined for Select2 selectWhereToLive 

Thoughts? 思考?

Edit 1: 编辑1:

The above simple_form_for call is producing this HTML: 上面的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="" />

Indicating that the id attribute is being properly set. 指示正确设置了id属性。

Edit 2 - Updated 编辑2 - 更新

As @moonfly suggested, I tried adding as: :select to the f.input_field - both with as: :autocomplete included and not included. 正如@moonfly建议的那样,我尝试添加as: :selectf.input_field - 两者都包含as: :autocomplete包含但未包含。

The resulting HTML without as: :autocomplete was this: 生成的HTML没有as: :autocomplete是这样的:

<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>

It pre-populates 2 option values 'Yes' and 'No'. 它预先填充2个选项值“是”和“否”。 Not quite sure why, but that is what it does. 不太清楚为什么,但这就是它的作用。

Update 更新

So I had changed the jquery selector to look for input#ID , and forgot. 所以我更改了jquery选择器以查找input#ID ,并忘了。 So I set that back and now it is generating the select box - but it is giving me those 2 Yes & No options. 所以我把它设置回来,现在它正在生成选择框 - 但它给了我2个是和否选项。 Not quite sure why it is doing that. 不太清楚为什么会这样做。 It's not returning the values in from my url attribute. 它没有从我的url属性返回值。

Edit 3 编辑3

@harish-shetty's suggestion seems to be working. @ harish-shetty的建议似乎有效。 But now, after it has successfully found the records via autocomplete and using the select2 menu, it is bypassing the setter method I have on my search.rb model. 但现在,在通过自动完成并使用select2菜单成功找到记录之后,它绕过了我在search.rb模型上的setter方法。

Basically, what I want to happen is, once the user has finished filling out the form - and I have all the IDs/names for the neighborhoods they want, I want to create a new record in search_neighborhoods for those IDs. 基本上,我想要发生的是,一旦用户填写完表单 - 并且我拥有他们想要的社区的所有ID /名称,我想在search_neighborhoods为这些ID创建一个新记录。

So these are the methods I have: 所以这些是我的方法:

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

My SearchController.rb 我的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

This is what a request looks like right now - which shows that no search_neighborhood records are being created: 这就是请求现在看起来的样子 - 这表明没有创建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

The select2 plugin supports auto-completion. select2插件支持自动完成。 You can use the native auto-completion as follows: 您可以使用本机自动完成,如下所示:

<%= 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 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);
        }
      }

    });
  });
});

Make sure the action at autocomplete_neighborhood_name_searches_path returns a json array of hashes. 确保autocomplete_neighborhood_name_searches_path的操作返回一个散列的json数组。 Each hash should contain id and name fields. 每个哈希应包含idname字段。 The term for auto-completion is passed via the query parameter name . 自动完成的术语通过查询参数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

Your search model: 您的搜寻模型:

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    

I believe you need to attach select either to select tag (then it reads the data from it) or to input hidden tag, then you need to provide 'query' function. 我相信你需要选择选择标签(然后从中读取数据)或输入隐藏标签,然后你需要提供'查询'功能。 In your case it is attached to an input tag, and thus looks for a query function. 在您的情况下,它附加到输入标记,从而查找查询函数。 Try setting as: :select on your f.input_field call. 尝试设置as: :selectf.input_field调用中as: :select

Use as: :select with collection is regular way to for select2. 用作:: select with collection是select2的常规方法。 Binding autocomplete on select2 is a javascript matter. 在select2上绑定自动完成是一个javascript问题。

This is my code sample. 这是我的代码示例。 but does not have autocompletion. 但没有自动完成功能。 https://gist.github.com/kuboon/f692d9a844c0ff5877c8 https://gist.github.com/kuboon/f692d9a844c0ff5877c8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM