I have the following code in my controller
class BooksController < ApplicationController
expose(:search) { search_books }
expose(:search_results) { load_results }
def search_books
search = Book.ransack(params[:q])
search.sorts = 'updated_at desc' if search.sorts.empty?
search
end
def load_results
search.result(distinct: true)
end
end
In my view I have lots of ransack search fields setup for the various book attributes i.e. title_eq
, body_cont
etc.
When I click the search button an the fields are empty Ransack still sends the params through the q:
param, even when they're empty. i.e. Parameters: {"utf8"=>"✓", "q"=>{"title_eq"=>"", "book_eq"=>""}
etc.
I've searched inside Ransack to see whether they have a method to tell whether the params are empty but I can't find one. What's the best way to handle this?
When you are fine with removing all blank search parameters, then you can call compact_blank
to only return key/values from the params
that have a value present.
params = ActionController::Parameters.new({q: { title: '', body: 'foobar'}})
params[:q].compact_blank
#=> #<ActionController::Parameters {"body"=>"foobar"} permitted: false>