Search code examples
ruby-on-railssearchcheckboxbooleanransack

How to filter boolean attribute with Rails Ransack?


In my Rails App I have an episode model. Each episode does have a boolean attribute cached which tags the episode as cached.

So episode.cached? returns true if the episode is cached.

I want to add a checkbox to my search form that makes it possible to show only cached episodes in the search result. I use the ransack gem to build my searches.

This is my current search form:

<%= search_form_for @query, url: playlist_management_search_path(channel_playlist: @channel_playlist.id), method: :get, remote: true do |f| %>
    <%= f.text_field :title_or_subtitle_cont, :placeholder => "Verzeichnis durchsuchen", :id => "search-input-field" %>
    <%= f.check_box_tag :cached_true, 1, :checked => @query.cached_true %>
    <%= f.submit "Search", :class => "prefix button" %>
<% end %>

With <%= f.check_box_tag :cached_true, 1, :checked => @query.cached_true %> I tried to get a checkbox that does what I described above. However it does not work. It says undefined method 'cached_true' for nil:NilClass.

So: How can I make a checkbox like "Only show me episodes with cached = true"?


Solution

  • Found the solution myself:

    <%= f.check_box :cached_true %>
    <%= f.label :cached_true %>
    

    The check_box_tag is only required if you want to loop through a couple of elements and add a check box for each of them.