【发布时间】: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