【问题标题】:How to return records of associated models using Typeahead?如何使用 Typeahead 返回关联模型的记录?
【发布时间】:2017-04-20 21:22:30
【问题描述】:

我正在使用twitter-typeahead-rails gem,它是基于typeahead 和bloodhound 构建的。当用户在搜索栏中输入内容时,我使用它通过 AJAX 返回结果。现在,它搜索我的模型Product 的实例,其中product.name 与搜索键匹配。这部分效果很好。

我想要做的是返回关联记录以及原始结果。我的Product 与Merchant 有belongs_to 关系。例如,当我输入搜索键时,我希望结果还列出与每个产品关联的商家,如下所示:

return "<div>" + product.name + product.merchant.name +</div>";

但现在,添加 product.merchant.name 会破坏该功能,因此我认为商家未包含在 JSON 中。如何包含它?

控制器

def typeahead
  q = params[:query]
  render json: Product.where('name like ?', "%#{q}%")
end

HTML/JS

<%= form_tag products_path, :method => :get do %>
  <%= text_field_tag :search, params[:search], id:"typeahead" %>
    <%= image_tag("Go.png", type:"submit") %>
<% end %>


<script type="text/javascript">
  $(document).ready(function(){
    var bloodhound = new Bloodhound({
      datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
      },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: '/typeahead/%QUERY'
    });
    bloodhound.initialize();

    $('#typeahead').typeahead(null, {
      displayKey: function(product) {
        return "" + product.name + "";
      },
      source: bloodhound.ttAdapter(),
      templates: {
        suggestion: function (product) {
          var thing_url = "<%=root_url%>pages/"
          return "<div>" + product.name + </div>";
        }
      }
    });
  });
</script>

宝石文件

gem 'twitter-typeahead-rails', '0.10.5'

更新:

我尝试在查询中包含Merchant:

Product.includes(:merchants).where('name like ?', "%#{q}%")

然后尝试在结果中返回merchant.name:

return "<div>" + product.name + product.merchant.name </div>";

但添加 product.merchant.name 会完全破坏该功能,所以现在我根本没有得到任何结果。

【问题讨论】:

    标签: javascript ruby-on-rails json typeahead.js bloodhound


    【解决方案1】:

    当您渲染为 JSON 时,您必须明确告诉 ActiveModel Serializer 包含关联的对象。

    渲染 :json => @products, :include => {:merchant=> {:only => :name}}

    【讨论】:

      【解决方案2】:

      尝试像这样在查询中包括商家

      Product.includes(:merchants).where('name like ?', "%#{q}%")
      

      【讨论】:

      • 我更新了我的问题。我正在尝试在结果中打印 Mercer.name,但 product.merchant.name 完全破坏了我的功能。如何在结果中访问 merchant?
      • 尝试获取第一个商家名称。我假设黑白产品和商家之间存在多对多关系。使用“product.merchants.first.name”而不是“product.merchant.name”
      • 否,Merchant has_many of Product,Product belongs_to Merchant。不幸的是,我无法查看错误,因为它都是通过 ajax 完成的,但是使用 hrynaud 的代码,product.merchant.name 终于可以工作了。
      【解决方案3】:

      您可以将用户ID添加到产品中,例如owner_id,然后您也可以使用查询

      @owner = User.find_by(id: @product.owner_id)
      

      【讨论】:

      • 但是product 是作为javascript 变量返回的。我如何将它传递到 Rails 查询中?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多