I have a boolean attribute (published) in my model book
and I wish to filter all books using checkboxes on that value.
class Book < ActiveRecord::Base
attr_accessible :published
end
That means I'd like something like eq_any
but for true
or false
. Is there a way to do this using Ransack?
UPDATE
I'd like users to be able to select only published books, only unpublished books and any book. So a single checkbox won't do.
I have solved this by using a select list with three options: "All", "Yes" and "No"
The query string for published_true will look like this:
q[published_true]=1
1 will return published booksq[published_true]=0
0 will return unpublished booksq[published_true]=
blank – will return both published and unpublished booksThe choosen answer works fine, but, at least in 2016, something better can be written. Leveraging on the "eq" functionality allows to remove some configuration. The final result is:
Renan, you can do this using the 'true' and 'false' predicates (other predicates are listed in the documentation link below).
In your form, your checkbox code would look something like this:
So, in your form, checking the first checkbox (published_true) would return all books where published is true, checking the second box (published_false) would return all books where published is false (unplublished), and submitting the form without checking either box would return all books.
More information can be found in the documentation here: https://github.com/ernie/ransack/wiki/Basic-Searching