simple_enum: Upgrading from 1.x to 2.x, missing accessors

I’m currently in the process of upgrading my Rails application from 3.2 to 4.0 (and upwards to 5.1 but that’s another story). As part of that upgrade, I changed simple_enum version from 1.6.9 to 2.3.1.

I find that newer accessors are not working, especially scopes.

Here is my model

class Season < ActiveRecord::Base
  as_enum :name, low: 0, medium: 1, high: 2
end

When I try finding the low season (or seasons), it will fail

Season.low #fail
Season.lows #fail

# error
NoMethodError: undefined method `lows' for #<Class:0x007f8415a11f08>

I believe it is because the accessor method where not generated at the time of the migration. Is there a way I can make it work?

I managed to get it working using the column_name but I believe it limits the use of simple_enum πŸ™ƒ

Season.where(name_cd: 0)

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 21 (4 by maintainers)

Commits related to this issue

Most upvoted comments

Great news, @drobny this fixes it πŸŽ‰ Thanks a lot.

I updated my sample repository to reflect the different possibilities.

Here is an extract:

EDIT: Fixed! βœ…

The issue was solved by @drobny; it was caused by pluralize_scopes getting confused as an option.

The solution is either to add options as an array, this maps to default arrays indices starting at 0

as_enum :name, [:low, :medium, :high], pluralize_scopes: false

# rails console
> Season.low
=> #<ActiveRecord::Relation [#<Season id: 3, created_at: "2018-04-03 09:15:40", updated_at: "2018-04-03 09:15:40", name_cd: 0>]>

Or to add options as a hash specifying the value to map to the enum

# you can specify whichever integer you like
as_enum :name, { low: 1, medium: 2, high: 3 }, pluralize_scopes: false


# rails console
# NOTE: difference is `name_cd` which is 1 instead of 0
> Season.low
=> #<ActiveRecord::Relation [#<Season id: 3, created_at: "2018-04-03 09:15:40", updated_at: "2018-04-03 09:15:40", name_cd: 1>]>

Actually @nicolasrouanne you could do something like

as_enum :name, { low: 1, medium: 2, high: 3 }, pluralize_scopes: false

with the current implementation which should allow you to do what you are describing πŸ‘