I'm trying to use the filterrific gem on a rails app to filter cities by a price lower than $1000 for example. - https://github.com/jhund/filterrific
but can't seem to set it up, i've added the code to the model and controllers but I get undefined method `sorted_by' for #<City::ActiveRecord_Relation:0x00007fc191173040> Did you mean? sort_by
method `sorted_by' for #<City::ActiveRecord_Relation:0x00007fc191173040> Did you mean? sort_by
Model -
class City < ApplicationRecord
has_one :guide, dependent: :destroy
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: %i[
sorted_by
search_query
with_created_at_gte
]
)
end
Controller -
class CitiesController < ApplicationController
def index
@cities = City.all
(@filterrific = initialize_filterrific(
City,
params[:filterrific]
)) || return
@cities = @filterrific.find.page(params[:page])
respond_to do |format|
format.html
format.js
end
end
Schema -
create_table "cities", force: :cascade do |t|
t.string "name"
t.string "internet"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "weather"
t.string "image"
t.string "country"
t.string "price"
end
It looks like you have copied and pasted the example from the documentation without really understanding what you are trying to do.
The error message is coming from your default_filter_params here:
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' }, <<<
...
)
For this to work you need a sorted_by scope which takes a parameter 'created_at_desc'. There are examples in the documentation here: http://filterrific.clearcove.ca/pages/active_record_scope_patterns.html
An example for the sorted_by scope would be:
scope :sorted_by, (lambda do |sort_option|
direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
case sort_option.to_s
when /^created_at_/
order("cities.created_at #{ direction }")
when /^name_/
order("cities.name #{ direction }")
else
raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
end
end)
to filter by price you will also need a scope like so:
scope :with_price_lte, (lambda do |price|
where('price >= ?', price)
end)
so your model filterrific clause should look like:
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: %i[
sorted_by
with_price_lte
]
)
There's more to it as you have to have a filterrific form in your view which returns the parameters for your scopes and an index.js.erb view which updates your list of cities, but this should help you get a little further.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.