Reputation: 1931
I have a model that has a boolean field called ignored
. What I did right up to this point is not display records which have this field set to true by having a default_scope where(:ignored => false)
.
Now, in my Ransack search form I would like to have a checkbox named Include ignored
so the table would also display the records which are ignored along with the ones which aren't.
I got as far as adding the checkbox to my search form f.check_box(:ignored_eq)
but when checking this, the list will display ONLY the ignored records. How do I display records in all states when checking this box?
Controller:
def index
@q = Venue.search(params[:q])
@venues = @q.result.page(params[:page]).per_page(15)
end
Search form (HAML):
= search_form_for @q, url: [:admin, :venues] do |f|
= f.text_field :name_cont
= f.text_field :locality_name_cont
= f.text_field :categories_name_cont
= f.check_box :ignored_eq
= content_tag :button, type: :submit, class: 'btn' do
= content_tag(:i, "", class: "icon-search")
= t("helpers.links.search")
The desired functionality is: when I enter the page I want to have only the ones that have ignore = false listed and have the box unchecked. When I check the box and submit the form I want to have ignored as well as non-ignored ones displayed. Is this possible with Ransack?
Upvotes: 2
Views: 1616
Reputation: 8295
What you can do is use the rewhere AR method.
and have something like that for the ignored
flag:
def index
@q = Venue.search(params[:q])
@q = @q.rewhere("ignored = 0 OR ignored = 1") if params[:ignored_eq] == 1
@venues = @q.result.page(params[:page]).per_page(15)
end
you can also use the unscoped method to clear the default_scope
def index
if params[:ignored_eq] == 1
@q = Venue.unscoped.search(params[:q])
else
@q = Venue.search(params[:q])
end
@venues = @q.result.page(params[:page]).per_page(15)
end
which is prettier (IMO)
Upvotes: 1