Eq_any for boolean attributes - ransack

I have a boolean attribute (published) in my book model and I want to filter out all books using checkboxes for this value.

 class Book < ActiveRecord::Base attr_accessible :published end 

This means that I would like something like eq_any , but for true or false . Is there a way to do this with Ransack?

UPDATE

I would like users to be able to select only published books, only unpublished books, and any book. Therefore, one flag will not do.

+4
source share
3 answers

I solved this using a select list with three options: "All", "Yes" and "No"

 = select :q, :published_true, [['Yes', 1], ['No', 0]], { include_blank: 'All', selected: params[:q] ? params[:q][:published_true] : '' } 

The query string for publish_true will look like this:

q[published_true]=1 1 will return published books

q[published_true]=0 0 will return unpublished books

q[published_true]= blank - will return both published and unpublished books

+3
source

Renan, you can do this using the predicates 'true' and 'false' (other predicates are listed below in the documentation).

In your form, your flag code will look something like this:

 <%= f.checkbox :published_true %> <%= f.checkbox :published_false %> 

So, in your form, checking the first flag (publish_true) will return all the books that are published, it’s true, checking the second field (publish_false) will return all published books that were published, false (not published) and send the form without checking either box will return all books.

Further information can be found in the documentation: https://github.com/ernie/ransack/wiki/Basic-Searching

+1
source

The selected answer works fine, but at least in 2016, something better might be written. Using the eq function allows you to delete some configuration. Final result:

 <%= f.select :published_eq, [['Yes', true], ['No', false]], include_blank: 'All' %> 
0
source

Source: https://habr.com/ru/post/1489912/


All Articles