Created
October 29, 2013 20:45
-
-
Save meinac/7222298 to your computer and use it in GitHub Desktop.
using scopes on ransack search and sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#paste this code in your ransack.rb initializer | |
#if you want to use scopes on search or sort please use Class.ransack_with_scopes instead of Class.search | |
Ransack::Adapters::ActiveRecord::Base.class_eval do | |
def ransack(params = {}, options = {}, scope_used_on_sort = false) | |
Ransack::Search.new(self, params, options, scope_used_on_sort) | |
end | |
def ransack_with_scopes(params = {}, options = {}) | |
scope_used_on_sort = false | |
ransack_scope = self | |
ransack_params = {} | |
(params||{}).each_pair do |k,v| | |
if ransack_scope.respond_to?(k) | |
ransack_scope = (v == true) ? ransack_scope.send(k) : (ransack_scope.method(k.to_sym).arity <= 0 ? ransack_scope.send(k) : ransack_scope.send(k, v)) | |
else | |
#maybe its a s parameter for sorting | |
scope_name = "sort_by_" + v.to_s.gsub(" ", "_") | |
if ransack_scope.respond_to?(scope_name) | |
ransack_scope = ransack_scope.send(scope_name) | |
scope_used_on_sort = true | |
end | |
ransack_params.merge!(k => v) | |
end | |
end | |
ransack_scope.ransack(ransack_params, options, scope_used_on_sort) | |
end | |
end | |
Ransack::Search.class_eval do | |
def initialize(object, params = {}, options = {}, scope_used_on_sort = false) | |
@scope_used_on_sort = scope_used_on_sort | |
(params ||= {}).delete_if { |k, v| v.blank? && v != false } | |
@context = Ransack::Context.for(object, options) | |
@context.auth_object = options[:auth_object] | |
@base = Ransack::Nodes::Grouping.new(@context, 'and') | |
build(params.with_indifferent_access) | |
end | |
def scope_used_on_sort? | |
@scope_used_on_sort | |
end | |
end | |
Ransack::Adapters::ActiveRecord::Context.class_eval do | |
def evaluate(search, opts = {}) | |
viz = Ransack::Visitor.new | |
relation = @object.where(viz.accept(search.base)) | |
if search.sorts.any? && !search.scope_used_on_sort? | |
relation = relation.except(:order).reorder(viz.accept(search.sorts)) | |
end | |
opts[:distinct] ? relation.select("DISTINCT #{@klass.quoted_table_name}.*") : relation | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this patch it is ok for my project!