Search code examples
ruby-on-railselasticsearchruby-on-rails-5searchkick

Searchkick how to display a joined table value for bucket key


I have a table called projects that has a bunch of fields. I joined to a project_status table to get status information. In outputting the different bucket keys, I am displaying the value of the proj_status_id (1, 2, 3, etc.) What I want to do is to display the statusdescr field from the joined table instead of the numeric proj_status_id.

Any thoughts on how to do that? Here is my index method of the projects controller:

    args = {}
    args[:projtype] = params[:projtype] if params[:projtype].present?
    args[:proj_status_id] = params[:proj_status_id] if params[:proj_status_id].present?
    args[:created_at] = params[:created_at] if params[:created_at].present?
    @projects = Project.joins(:proj_status).order("created_at DESC").search "*", where: args, aggs: {projtype: {}, proj_status_id: {}, created_at: {}}

This is where I display the bucket info:

    <% @projects.aggs["proj_status_id"]["buckets"].each do |bucket| %>

    <span class="text-body d-flex justify-content-between align-items-center py-2 px-4">
      <% if params[:proj_status_id] == bucket["key"].to_s %>
        <div> <strong><%= link_to bucket["key"], request.params.merge(proj_status_id: bucket["key"]) %></strong> (<%= bucket["doc_count"]%>)</div>
      <% else %>
        <div><%= link_to bucket["key"], request.params.merge(proj_status_id: bucket["key"]) %> (<%= bucket["doc_count"]%>)</div>
      <% end %>
    </span>

    <% end %>

Any thoughts or suggestions are appreciated.


Solution

  • You need to index project_status also. Add the below code to your projects model:

    def search_data
      attributes.merge(
        project_status_statusdescr: self.project_status.try(:statusdescr)
      )
    end
    

    After adding the above code, don't forget to reindex.