Typeahead填充活动记录对象

时间:2016-01-13 16:18:53

标签: jquery ruby-on-rails search typeahead.js

我正在使用rails 4而我正试图让它与最新的typeahead一起使用。下拉列表显示匹配的活动记录对象的所有属性,而不仅仅是我想要的名称。

item.rb

  def self.search(search)
    if search
      where(['lower(name) LIKE ?', "%#{search}%"])
    else
      Item.all
    end
  end

items_controller.rb

  def index
    @items= Item.search(params[:query])
  end

  def typeahead
    render json: Item.where('name ilike ?', "%#{params[:query]}%")
  end

_header.html.erb

.
.
.
<script>
$(document).ready(function(){
    var bloodhound = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      limit: 10,  
      remote: {url: '/typeahead/%QUERY',
               wildcard: '%QUERY'}  
    });
    bloodhound.initialize();

    $('#typeahead').typeahead(null, {
      name: 'name',
      source: bloodhound.ttAdapter()
    });

    $('#typeahead').bind('typeahead:selected', function(event, datum, name) {
      window.location.href = '/items/' + datum.id;
    });
  });
</script>

config/routes.rb

get 'typeahead/:query', to: 'items#typeahead'

我可以去/typeahead/:query.json,它似乎正在按预期工作。

1 个答案:

答案 0 :(得分:1)

请参阅<{p}}上的documentation

  

display - 对于给定的建议,确定字符串   代表它。这将在设置值时使用   选择建议后的输入控制。可以是一把钥匙   字符串或将建议对象转换为   串。默认为字符串化建议。

$(document).ready(function() {
  var data = [{
    "id": 4,
    "name": "Flexidy",
    "description": "Impedit libero veniam sit molestias quae.",
    "created_at": "2016-01-07T15:26:45.305Z",
    "updated_at": "2016-01-07T15:26:45‌​.305Z",
    "created_by": null,
    "status": 1
  }, {
    "id": 5,
    "name": "Plexidy",
    "description": "Impedit libero veniam sit molestias quae.",
    "created_at": "2016-01-07T15:26:45.305Z",
    "updated_at": "2016-01-07T15:26:45‌​.305Z",
    "created_by": null,
    "status": 1
  }];
  var bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: $.map(data, function(item) {
      return {
        value: item.name
      }
    })
  });
  bloodhound.initialize();

  $('#typeahead').typeahead({
    highlight: true
  }, {
    name: 'name',
    display: 'name',
    limit: 10,
    templates: {
      suggestion: function(data) {
        console.log(data);
        var details = "<div>" + data.value + "</div>";
        return details
      }
    },
     source: bloodhound.ttAdapter()
  });

  // $('#typeahead').bind('typeahead:selected', function(event, datum, name) {
  //   window.location.href = '/items/' + datum.id;
  // });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>



<div class="bs-example">
  <input type="text" id="typeahead" />
</div>