Hi I am using Filterrific Gem to add searching and filtering functionalities for my users page.
The Searching works just fine, but I got undefined method
[]' for nil:NilClass` error when I tried to implement the "sorted by" filtering.
I refer the Filterrific documentation here: http://filterrific.clearcove.ca/pages/action_view_api.html
Here are my codes:
index.html.erb
<div class="well">
<%= form_for_filterrific @filterrific do |f| %>
<div>
<%= f.text_field( :search_query, id: "filterrific-no-ajax-auto-submit" ,class: 'form-control', placeholder: "Search users...") %>
</div>
<div>
Sorted by
<% f.select(:sorted_by, @filterrific.select_options[:sorted_by]) %>
</div>
<% end %>
</div>
<div class="row">
<%= render(
partial: 'users/list',
locals: { users: @users }
) %>
</div>
model.rb
filterrific(
default_filter_params: { sorted_by: 'first_name_asc' },
available_filters: [
:sorted_by,
:search_query,
:with_created_at
]
)
scope :sorted_by, lambda { |sort_option|
direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
case sort_option.to_s
when /^first_name/
order("users.first_name #{ direction }")
else
raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
end
}
users_controller.rb
def index
@filterrific = initialize_filterrific( User, params[:filterrific] ) or return
@users = @filterrific.find.page(params[:page]).order('first_name ASC')
respond_to do |format|
format.html
format.js
end
end
Here is the screenshot of the error:
Please help. Thanks!
While initialization in your controller. The params doesnt contain select_options. They shall contain select_options. Right now it looks as:
"filterrific"=>{"search_query"=>""}
it shall be something like
"filterrific"=>{"search_query"=>"", "select_options"=>YOUR-OPTIONS}