Search code examples
ruby-on-railssearchelasticsearchviewchewy-gem

Link to the Model element from search results (Chewy, Rails)


I have implemented a search for User model (Elasticsearch using Chewy gem).

views/search/search.html.erb:

<%= form_tag search_path, method: "get" do %>
    <%= label_tag(:q, "Search by name/ surname/ email:") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Search") %>
<% end %>

<% @results.each do |r| %>
   <%= r.name %> 
   <%= r.surname %>,
   <%= r.email %>, 
<% end %>

routes.rb:

devise_for :users
resources :users, only: [:show], controller: :profiles

What I need is to add a link to a user for each search result line. (How to connect Chewy users indexes with user pages)

update:

I changed the last paragraph in search.html.erb to:

<% @results.each do |r| %>
<%= link_to r.name, user_path(r) %> 
<%= r.surname %>,
<%= r.email %>, 
<% end %>

The search results are clickable now but I get the following error:

ActiveRecord::RecordNotFound in ProfilesController#show Couldn't find User with 'id'=#UsersIndex::User:0x007fa1050ebed0>

my profiles_controller.rb:

class ProfilesController < ApplicationController
skip_before_action :authenticate_user!

def show
@user = User.find(params[:id])   //this line gets an error
end
end

Solution

  • have a look to rake routes which is listing all routes and their names

    resources :name is generating all the default routes (where you just specified to make the show_route)

    <% @results.each do |r| %>
       <%= link_to r.name, user_path(r.id) %> 
       <%= r.surname %>,
       <%= r.email %>, 
    <% end %>
    

    or, maybe more advanced

    <% @results.each do |r| %>
       <%= link_to user_path(r.id) do %> 
         <%= r.name %>,
         <%= r.surname %>,
         <%= r.email %>
       <% end %> 
    <% end %>
    

    you are throwing the id of the result into the user_path() helper, which will genreate /user/12