Search code examples
ruby-on-railsransackhas-scope

Include selected has_scope on ransack search filter


I am attempting to combine has_scope and ransack.

Each of these components is working perfectly by themselves. However, when I attempt to combine them, they overwrite each other. For example, if I select a scope, the results are appropriately filtered, but once I use the search_form from ransack to filter the results further, the scope is then removed. The inverse is also true.

How can this be achieved?

Thanks for your help.

Please see my attempt below.

has_scope :upward_trending, :type => :boolean
has_scope :downward_trending, :type => :boolean
has_scope :all, :type => :boolean

def index
    @has_scope = apply_scopes(Product).all
    @q = @has_scope.search(params[:q])
    @products = apply_scopes(@q.result.page(params[:page]).per(30))
end

Solution

  • With Ransack's new ransackable_scopes functionality, there is no longer a need for has_scope

    I can do it like this:

    def self.ransackable_scopes(auth_object = nil)
        [:upward_trending, :downward_trending, :seven_days, :thirty_days, :six_months, :twelve_months, :all_time]
    end
    

    And then I am able to call these scopes within Ransack as needed.

    So to answer the question, with this new functionality, the scopes are already integrated and we are all good.