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?
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?
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]}
active
to integer .to_i
so You will get always 0
instead of proper value. –
Sheepshanks 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} %>
radio_buttons
? –
Indispose Below works fine for all cases :draft, 'draft', 0, '0' in model
ransacker :status do |parent|
parent.table[:status]
end
ransacker in accepted answer of @qarol works but since OP is looking for a cleaner solution, you may also opt to combine enum defined scopes with ransack like the following:
Model.active.ransack(params_for_others).result
Model.not_active.ransack(params_for_others).result
These works properly.
You may check with: puts Model.active.ransack(onboarded_eq: true).result.to_sql
will print:
SELECT "model".* FROM "models" WHERE "models"."status" = 1 AND "users"."onboarded" = TRUE
however, beware of some issues when combining ransack + arel, e.g. GroupingError
PG::GroupingError: ERROR: column \"other_model.id\" must appear in the GROUP BY clause or be used in an aggregate function
© 2022 - 2024 — McMap. All rights reserved.