-
-
Save marcomontes/ff8af3c88c0aed986aba41ce496cc801 to your computer and use it in GitHub Desktop.
Filtering with Filterrific and PgSearch
This file contains 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
# index.js.haml | |
- js = escape_javascript(page_entries_info @properties) | |
$("#results_page_entries_info").html("#{ js }"); | |
- js = escape_javascript(paginate @properties) | |
$("#results_paginate").html("#{ js }"); | |
- js = escape_javascript(render @properties) | |
$("#results_properties").html("#{ js }"); | |
# properties_controller.rb | |
class PropertiesController < ApplicationController | |
# GET /properties | |
def index | |
(@filterrific = initialize_filterrific( | |
Property, params[:filterrific], | |
select_options: { | |
sorted_by: Property.options_for_sorted_by, | |
with_purpose: Property.options_for_purpose | |
} | |
)) || return | |
@properties = @filterrific.find.page params[:page] | |
respond_to do |format| | |
format.html | |
format.js | |
end | |
end | |
end | |
class Property < ApplicationRecord | |
# Filters and Scopes | |
pg_search_scope :search_by_keywords, | |
against: %i[ | |
title | |
description | |
notes | |
], | |
using: { | |
tsearch: { prefix: true } | |
}, | |
ignoring: :accents | |
filterrific( | |
default_filter_params: { | |
sorted_by: 'created_at_desc', | |
with_purpose: 'sale' | |
}, | |
available_filters: %i[ | |
search_query | |
sorted_by | |
with_purpose | |
min_sale_value | |
max_sale_value | |
min_rent_value | |
max_rent_value | |
] | |
) | |
scope :min_sale_value, lambda { |value| | |
where('properties.sale_value >= ?', value) | |
} | |
scope :max_sale_value, lambda { |value| | |
where('properties.sale_value < ?', value) | |
} | |
scope :min_rent_value, lambda { |value| | |
where('properties.rent_value >= ?', value) | |
} | |
scope :max_rent_value, lambda { |value| | |
where('properties.rent_value < ?', value) | |
} | |
scope :search_query, lambda { |query| | |
search_by_keywords(query) | |
} | |
scope :with_purpose, lambda { |purpose| | |
where(purpose: [*purpose]) | |
} | |
scope :sorted_by, lambda { |sort_option| | |
# extract the sort direction from the param value. | |
direction = sort_option.match?(/desc$/) ? 'desc' : 'asc' | |
case sort_option.to_s | |
when /^created_at_/ | |
order("properties.created_at #{direction}") | |
when /^updated_at_/ | |
order("properties.updated_at #{direction}") | |
when /^title_/ | |
order("LOWER(properties.title) #{direction}") | |
else | |
raise(ArgumentError, "Ordenação inválida: #{sort_option.inspect}") | |
end | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment