1

I have an enum called access defined on an account model.

enum access: [:basic, :silver, :gold, :platinum]

which works fine, e.g. account.gold! sets the value to 'gold' and then account.access returns 'gold'. Accordingly, I should be able to list the hash of access values with the plural of acesss, but account.accesses, returns

NoMethodError: undefined method `accesses' for #<Account:0x00007f9e7827e408>
Did you mean?  access
               access?
           access=

If I do 'access'.pluralize it returns accesses, so why isnt account.accesses working?

Obromios
  • 15,408
  • 15
  • 72
  • 127
  • Are you sure that RoR pluralizes enums? I know it will do that with database entities, but I don't see the point of doing that with an enum. – Robert Harvey Nov 25 '18 at 22:25
  • Yes it does, see https://stackoverflow.com/a/25570511/1299362, and it can be useful because you can write methods that will continue to work after someone adds a different value to the enum. – Obromios Nov 25 '18 at 22:32

2 Answers2

1

I think it should work if you try the plural form:

Account.accesses

The mappings are exposed through a class method with the pluralized attribute name.

Check the guide here: https://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

John Baker
  • 2,315
  • 13
  • 12
1

The plural method needs to be called on the model class (not on the instance of the class):

2.5.3 :001 > Account.accesses
 => {"basic"=>0, "silver"=>1, "gold"=>2, "platinum"=>3}

See the example here. See the actual code here. It defines the method on the class.

Raj
  • 22,346
  • 14
  • 99
  • 142