I implemented Algolia's instantsearch on my Rails app. I use it to display a list of product as search results.
For the instant search implementation I followed Algolia's guide.
I created an Index called Products (on my Algolia account). It has a name, url, image, and an id (+ an objectID given by Algolia).
My application.js file with the Algoli search widgets:
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;
}
The code inside my index.html.erb view looks like this:
# 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>
Here is the result sent by Algolia (got it from the browser), don't know how to get the result variable inside the view/controller.
"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,
....
I can get the link like that :
<%= link_to "Voir", CGI::unescape(product_path("{{objectID}}")) %>
How can I retrieve the ruby object in my view ?
I try to do it :
<% product = Product.find("{{objectID}}") %>
or
<% product = Product.find("{{id}}") %>
But it's not working. How get I get the object inside the view/controller ?