Moosa
Moosa

Reputation: 3216

Rails - Filtering Searchkick Results using a model method

I'm using Searchkick on a Rails ecommerce project. Users can search product listings.

I have some conditions under which certain products are not displayed on the site (example, if inventory = 0, etc).

Based on the searchkick docs, I have my search method in the controller as @listings = Listing.search(params[:search]). This works as intended.

In my listing model, I have the below method that defines which listings are ok to be displayed.

class Listing < ActiveRecord::Base

    scope :listable, -> { 
    joins("INNER JOIN users
           ON users.id = listings.user_id
           AND users.hidelistings = 'f'") }

    def self.not_expired 
        listable.where('(listings.updated_at >= ? or user_id = ?) and inventory > ?', Date.current - 30.day, 24, 0)
    end

Based on the above, I want my searchkick method to say @listings = Listing.not_expired.search(params[:search]) but this doesn't work. How do I tell searchkick to only display results that meet the criteria?

Upvotes: 3

Views: 782

Answers (1)

Oshan Wisumperuma
Oshan Wisumperuma

Reputation: 1958

I faced the same issue. finally, had to add relevant fields and include that filtering logic into the Searchkick query.

however, that's really good. because it is super fast just search using elastic search. or else, when data get large, run two queries in both servers is unnecessary overhead.

in my first solution, I manually pluck filtered id and passed that to elasticsearch where clause, which we hit many issues.

Upvotes: 0

Related Questions