简体   繁体   中英

Why enum doesn't work as advetised in the documentation?

I have a model with this enum:

  enum food: { not_food: 0, is_food: 1 }

However it does not seem to work as expected:

2.4.4 :007 > Analyte.where( food: 'is_food').count
   (3.0ms)  SELECT COUNT(*) FROM "ANALYTES" WHERE "ANALYTES"."FOOD" = :a1  [["food", 0]]
 => 12709 
2.4.4 :008 > Analyte.where( food: 'not_food').count
   (3.1ms)  SELECT COUNT(*) FROM "ANALYTES" WHERE "ANALYTES"."FOOD" = :a1  [["food", 0]]
 => 12709 

Please note that in both cases ZERO is the query's argument.

Also I saw this https://medium.com/@elcortez/the-many-issues-with-rails-enum-36cfb2bec620 and this https://github.com/rails/rails/issues/32618

Should I use enum in my project or is it not worth it? I use Rails 4.2 if that matters.

And food is defined in the database like this:

#  food              :integer          default(0)

What you're attempting to do - using the enum key in a where - does not work until Rails 5. Compare the enum 4.2 docs to the 5.0 docs and you can see that for 5.0 the docs state:

Of course, you can also query them directly if the scopes don't fit your needs

This is what you are attempting doing, but note that the 4.2 docs make no mention of this approach.


Anyway, you can achieve similar with this slightly more long winded approach:

Analyte.where(food: Analyte.foods['is_food']).count

Don't forget the enum choices become scopes as well, so this will work:

Analyte.is_food.count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM