ruby-on-rails – 如何在simple_form中使用select2-rails?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何在simple_form中使用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.coffeefile:

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所建议的,我尝试添加为::选择到f.input_field – 两者都具有::包含autocomplete,不包括在内.

由此产生的HTML不作为: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>

它预先填充2个选项值“是”和“否”.不太确定为什么,但这是它的作用.

更新

所以我更改了jquery选择器来查找输入#ID,并忘记了.所以我把它放回来,现在它正在生成选择框 – 但它是给我那些2是&没有选项不太确定为什么这样做.它不是从我的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",["created_at",Wed,06 Mar 2013 09:09:55 UTC +00:00],["keywords",["listing_type_id",["max_price",["min_price",["neighborhood_id",["num_bathrooms",["num_bedrooms",["property_type_id",["square_footage",["updated_at",06 Mar 2013 09:09:55 UTC +00:00]]
   (32.2ms)  COMMIT
Redirected to http://localhost:3000/searches/29

解决方法

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,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,initSelection : function (element,callback) {
        if (saved) {
          callback(saved);
        }
      }

    });
  });
});

确保在autocomplete_neighborhood_name_searches_path中的操作返回一个哈希数组的json数组.每个哈希应包含id和name字段.自动完成的术语通过查询参数名称传递.

def autocomplete_neighborhood_name
    @neighborhood = Neighborhood.select("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

猜你在找的Ruby相关文章