【问题标题】:RAILS Algolia How to get the Ruby Object, Instantsearch.jsRAILS Algolia 如何获取 Ruby 对象,Instantsearch.js
【发布时间】:2017-12-27 10:22:25
【问题描述】:

我在我的 Rails 应用上实现了 Algolia 的即时搜索。我用它来显示产品列表作为搜索结果。

对于即时搜索实施,我遵循了 Algolia 的指南。

我创建了一个名为 Products 的索引(在我的 Algolia 帐户上)。它具有名称、url、图像和 id(+ 由 Algolia 提供的 objectID)。

我的带有 Algoli 搜索小部件的 application.js 文件:

    var search = instantsearch({
  // Replace with your own values
  appId: "1JJ5DY0CLA",
  apiKey: 'e24882443747d61c496efc4e17288a36', // search only API key, no ADMIN key
  indexName: 'Idea',
  urlSync: true
});


search.addWidget(
  instantsearch.widgets.searchBox({
    container: '#search-input',
    placeholder: 'Search for growth ideas',
    poweredBy: true
  })
);

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    hitsPerPage: 10,
    templates: {
      item: getTemplate('hit'),
      empty: getTemplate('no-results')
    }
  })
);

search.start();

function getTemplate(templateName) {
  return document.querySelector('#' + templateName + '-
template').innerHTML;
}

我的 index.html.erb 视图中的代码如下所示:

# Comment: this is the code to structure each result sent by the API
<script type="text/html" id="hit-template">
    <div class="product">
       <div class="product-title">  
          <h3>{{title}}</h3>
       </div>
       <div class="product-link">
          <%= link_to "Voir", CGI::unescape(product_path("
          {{objectID}}")) %>
       </div>
  </div>

这是Algolia发送的结果(从浏览器获取),不知道如何获取视图/控制器内部的结果变量。

"hits": [
    {
      "id": 1881,
      "name": "FOULARD NOA PRINT OFF WHITE/TERRA/GERANIUM",
      "female": true,
      "category": "Accessoires",
      "brand_id": 7,
      "url": "https://www.ekyog.com/foulard-noa-print-off-white/terra/geranium.html",
      "photos": [
        "https://www.ekyog.com/Imagestorage/imagesSynchro/556/790/e86cffa2bbbeea83a9d4bb7de0bbd5c368a6c9dd_B-FOU-288-P219.jpg",
        "https://www.ekyog.com/Imagestorage/imagesSynchro/556/790/4644f21ce6e8ddf8a1b3af053264c2c5429567d5_B-FOU-288-P219-CONF1.jpg"
      ],
      "price_cat": "0€ - 50€",
      "subcategory": "Echarpes & Foulards",
      "price_cents": 3400,
      ....

我可以得到这样的链接:

<%= link_to "Voir",  CGI::unescape(product_path("{{objectID}}")) %>

如何在我的视图中检索 ruby​​ 对象?

我试着去做:

<% product = Product.find("{{objectID}}") %>

<% product = Product.find("{{id}}") %>

但它不起作用。如何在视图/控制器中获取对象?

【问题讨论】:

    标签: ruby-on-rails algolia instantsearch.js


    【解决方案1】:

    您的 ERB 代码仅在页面呈现时进行评估。 您的link_to 将起作用,因为这只是生成一个字符串(例如/products/{{objectID}}),稍后将由前端更新。

    您不能使用这些变量来使用 Ruby 代码对它们进行实际操作。实际上,使用instantsearch.js,您无需重新加载页面即可动态检索结果,这意味着您只能访问 JavaScript 上下文。

    【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2017-01-03
    • 2017-11-29
    • 2018-04-04
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2016-05-27
    相关资源
    最近更新 更多