gazubi
gazubi

Reputation: 561

How do you query Active record with enums

I am trying this query and it is not working:

OrderFulfillment.where(shopper_id: shopper.id, fulfillment_status:  [:fulfillment_requested_assignment, :fulfillment_assigned, :fulfillment_shopping])

I am not sure why but I am unable to get querying using enums to work

Upvotes: 1

Views: 74

Answers (1)

Rob Wise
Rob Wise

Reputation: 5120

OrderFulfillment.where(shopper_id: shopper.id, 
                       fulfillment_status: OrderFulfillment
                         .fulfillment_statuses
                           .values_at([:fulfillment_requested_assignment,
                                       :fulfillment_assigned,
                                       :fulfillment_shopping]))

Rails isn't smart enough to know that you are passing keys and not values, so when you were passing the statuses straight like that it was looking for the wrong values (it changed them to null because it didn't understand). The enums are physically stored as integers, so that's what you actually need to use in the query. Therefore, you can use the Rails-provided fulfillment_statuses method to grab a hash of the key/value pairs of the enum, and then the values_at method of the hash to get the values for the array of keys you pass in.

Upvotes: 1

Related Questions