11

I've got a table, 'jobs' with a enum field 'status'. status has the following enum set:

enum status: [ :draft, :active, :archived ]

using ransack, how do I filter the table for, say, all active records?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Will
  • 4,498
  • 2
  • 38
  • 65

3 Answers3

22

You can declare own ransacker in model like this:

ransacker :status, formatter: proc {|v| statuses[v]} do |parent|
  parent.table[:status]
end

Then You can use default ransack syntax _eq to check equality like this:

Model.ransack(status_eq: 'active').result

Edit: If column name doesn't change you can skip block of code:

ransacker :status, formatter: proc {|v| statuses[v]}
qarol
  • 1,119
  • 1
  • 12
  • 17
  • Thanks. that works, but it seems like i might as well just use the param value and do a regular search. the code reads a bit better / simple that way. Adding a filter in ActiveAdmin worked without creating a ransacker, even though they use Ransack for their filtering. It seems odd it didn't work on the front end as easily. – Will May 19 '16 at 12:01
  • @Will Yeap, you can use just simple scope. It should work fine :) But problem appears when You can't skip using ransack. Without code mentioned above, it's going to always cast parameter `active` to integer `.to_i` so You will get always `0` instead of proper value. – qarol May 19 '16 at 12:27
9

This is something I use in my views for enums and ransack:

<%= f.select :status_eq, Model.statuses.to_a.map { |w| [w[0].humanize, w[1]] },
                         {:include_blank => true} %>
Andrew Cetinic
  • 2,805
  • 29
  • 44
0

Below works fine for all cases :draft, 'draft', 0, '0' in model

ransacker :status do |parent|
  parent.table[:status]
end
Bhaveshkumar
  • 479
  • 4
  • 9