【发布时间】:2017-07-11 00:00:53
【问题描述】:
我在我的 Rails 应用上实现了 Algolia 的即时搜索。我用它来显示产品列表作为搜索结果。
每个产品都有一个保存按钮。我想检索每个结果的 id 以将其传递到 link_to 标记中。
对于即时搜索实现,我关注了Algolia's guide。
我创建了一个名为 Products 的索引(在我的 Algolia 帐户上)。它有一个标题和一个 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 视图中的代码如下所示:
<div id="hits"></div>
# 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-save">
# Comment: where I'd like to replace product_id by the result id
<%= link_to "save", product_path(product_id, current_user), method: :post %>
</div>
</div>
如何检索结果的 id 以将其传递给 link_to 标记?
这是Algolia发送的结果(从浏览器获取),不知道如何获取视图/控制器内部的结果变量。
{
"results":
[
{
"hits":
[
{
"title":"Product title1",
"id":65,
"objectID":"344300262"
},
{
"title":"Product title2",
"id":66,
"objectID":"344300263"
}
]
}
]
首次测试:
从 algolia 示例(请参阅上面的代码)我发现我可以将结果属性检索到 html 中,如下所示:{{id}}。但我不确定它是什么样的“对象”。
我可以用<%= "{{id}}" %>在页面上显示id。但在 Ruby 中,它被解释为字符串 {{id}},所以我不能像下面这样使用它:
<%= link_to "save", product_path("{{id}}", current_user), method: :post %>
此外,我看到有一个 get_object 方法可以在我的索引上使用来检索整个 Algolia 的对象,如下所示:
index.get_object("objectID"),objectID 是 integer。
但是关于id,我不知道如何获取当前显示结果的objectID。
如果我的问题需要任何改进,我很乐意让它更易于理解。告诉我吧。
【问题讨论】:
-
从 Algolia 搜索得到结果后,你能告诉我结果变量吗
-
我添加了 application.js 内容,Algolia 发送的响应(从浏览器获取)是网络选项卡。但我不确定我怎么不能从视图中得到它。 @迪亚斯
标签: ruby-on-rails ruby algolia