我在我的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}}") %>但它不起作用。如何获取视图/控制器中的对象?
发布于 2017-07-21 19:44:25
您的ERB代码仅在页面呈现时计算。您的link_to将工作,因为这只是生成一个字符串(例如/products/{{objectID}}),该字符串稍后将由前端更新。
在Ruby代码中,您不能使用这些变量来对它们进行实际操作。实际上,使用instantsearch.js可以在不重新加载页面的情况下动态检索结果,这意味着您只能访问JavaScript上下文。
https://stackoverflow.com/questions/45236419
复制相似问题