Skip to content

Rails where query should see value is an enum and convert a string #17226

@justin808

Description

@justin808

Suppose you have this situation:

MyModel.where(some_enum: "enum_value")

Well, that currently doesn't work. You have to do this:

MyModel.where(some_enum: some_enums["enum_value"])

That is so that "enum_value" is converted to the proper integer value.

Even worse, the first query currently does not throw an error and converts the string (any string) to an integer value of zero!

Here's an actual console trace showing this:

[17] (pry) main: 0> Manager.where(dominant_product_type: "hedge_fund").count
   (8.3ms)  SELECT COUNT(*) FROM "managers"  WHERE "managers"."dominant_product_type" = 0
3980
[18] (pry) main: 0> Manager.where(dominant_product_type: "liquidity_fund").count
   (8.4ms)  SELECT COUNT(*) FROM "managers"  WHERE "managers"."dominant_product_type" = 0
3980
[20] (pry) main: 0> Manager.where(dominant_product_type: Manager.dominant_product_types["liquidity_fund"]).count
   (7.5ms)  SELECT COUNT(*) FROM "managers"  WHERE "managers"."dominant_product_type" = 1
22

Notice, zero is used in the first two queries. The third query is correct.

A related issue is this, using the example from the docs:

Should this code give the same result or different:

statuses = Conversation.select(:status).where.not(status: nil).distinct.map(&:status)

as compared to:

statuses = Conversation.distinct.where.not(status: nil).pluck(:status)

In the first case, you get back an Array with 2 strings: =["active",
"archived"]=. In the second case, you get back an Array with 2 integers: [0, 1].

If the core team deems this worthy, I could try my hand at a PR to implement this.

At the minimum, this seems worthy for the documentation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions