Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching on an Enum Field with Ransack

Tags:

ruby

ransack

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?

like image 997
Will Avatar asked May 16 '16 15:05

Will


2 Answers

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]}
like image 150
qarol Avatar answered Nov 19 '22 14:11

qarol


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} %>
like image 45
Andrew Cetinic Avatar answered Nov 19 '22 13:11

Andrew Cetinic