I want whole model return I have 2 models by using pg search in rails

72 Views Asked by At
  1. I want this form

    "data": [ { "id": 2, "searchable_type": "User", "email": "abc", "first_name": "abc", "last_name": "xyz", "created_at": "2022-08-05T09:40:18.986Z", "updated_at": "2022-08-05T09:40:18.986Z" }, { "id": 3, "searchable_type": "blog", "tittle": "user", "created_at": "2022-08-05T09:40:18.986Z", "updated_at": "2022-08-05T09:40:18.986Z" } ]

I want to return whole object for each model respectively by using Pg Search multi search it just return a content ,searchable_type and searchable_id as attached images belowIt is my postman image for blog returnIt is my postman image for user return [My search controller, User and blog models]

class Api::V1::SearchController < Api::V1::ApiController
  def index
    @query = params[:value]
    @results = PgSearch.multisearch(@query)
    render json: { data: @results}, status: :ok
  end
end


class Blog < ApplicationRecord
 include PgSearch::Model
 multisearchable against: [:id, :title, :created_at, :updated_at ]
end

class User < ApplicationRecord
  include PgSearch::Model
  multisearchable against: [:id, :email, :first_name, :last_name ]
end
1

There are 1 best solutions below

0
spickermann On

Change

@results = PgSearch.multisearch(@query)

to

@results = PgSearch.multisearch(@query).includes(:searchable).map(&:searchable)