mercredi 11 mai 2016

filter one model's results in a multiple model search

I am using PgSearch to search multiple models. I am also using Ancestry to build family trees.

For Co, one of the models that I search against, I want to exclude the results that don't have children. To explain further, there are Cotypes that cannot have children, so the respective Cos have no children. The latter are the ones that I don't want to have in the search results.

I tried to filter the search in the model level, by adding an if condition in the multisearchable scope. But it doesn't affect the results, I still can see the Cos without children.

class Co
    attr_accessible :name, :ancestry, :cotype_name, :cotype, :cotype_id, :parent_id, :parent

    belongs_to :cotype, inverse_of: :cos

    scope :with_children, ->() {
        joins(:cotype).where(cotypes: {can_have_children: true})
    }

    include PgSearch
    multisearchable against: [:name],
        :if => :with_children, #This line doesn't work. I still get the Cos without children in the results.
        using: {
            tsearch: {
                dictionary: "english",
                tsvector_column: 'tsv_content'
            }
        }
end


class CoType
    attr_accessible :name, :type, :type_id, :can_have_children

    belongs_to :type, class_name: "Ot", foreign_key: "type_id"
    has_many :cos, inverse_of: :cos

    scope :with_children, where(:can_have_children, true)
end


class SearchController < ApplicationController

    def index
        @results = PgSearch.multisearch(params[:query]).page(params[:page] || 1).per_page(params[:per_page] || 25)
    end
end

I tried to solve this issue by filtering the results in the search controller instead of the model.

@results = PgSearch.multisearch(params[:query]).reject{|r| r.searchable_type == "Co" and !r.searchable.cotype.can_have_children}

But this leads to another conflict where I cannot paginate anymore.

@results = PgSearch.multisearch(params[:query]).reject{|r| r.searchable_type == "Co" and !r.searchable.cotype.can_have_children}.page(params[:page] || 1).per_page(params[:per_page] || 25)

That's the error:

undefined method `page' for #<Array:0x007f15843a7d98>

Where is the best place to implement it, the controller or the model? Any idea of what is wrong with my tries? Thank you for any advice in advance!

Aucun commentaire:

Enregistrer un commentaire