Enum is not registering

Trying get view enum choices in rails console but its returning

ready-manager(dev)> InProcessingForm.rank
app/models/in_processing_form.rb:18:in `<class:InProcessingForm>': You tried to define an enum named "rank" on the model "InProcessingForm", but this will generate a instance method "pvt?", which is already defined by another enum. (ArgumentError)
	from app/models/in_processing_form.rb:1:in `<main>'
	from (ready-manager):1:in `<main>'

Here is the enum in my models .rb

  enum :rank, [
    :pvt,
    :pv2,
    :pfc,
    :spc,
    :cpl,
    :sgt,
    :ssg,
    :sfc,
    :msg,
    :first_sgt,
    :csm,
    :sgm,
    :sma,
    :wo1,
    :cw2,
    :cw3,
    :cw4,
    :cw5,
    :second_lt,
    :first_lt,
    :cpt,
    :maj,
    :ltc,
    :col,
    :bg,
    :mg,
    :ltg,
    :gen
  ] # Add more ranks as needed

By declaring that enum you will get the method pvt? automatically available to you but it seems it’s clashing with another definition of pvt? from another enum

By default, declaring an enum field adds setter and query instance methods to the model for each enum value.

class Member < ApplicationRecord
  enum :rank, [ :pvt, :pv2, :pfc ]
end

member.pvt! # equivalent to member.rank = :pvt
member.pvt? # => true, equivalent to member.rank == :pvt
member.pv2? # => false

To prevent collisions with other instance methods, you can use the prefix or suffix options. Set to true it will use the name of the field, or you can pass a custom value.

class Member < ApplicationRecord
  enum :rank, [ :pvt, :pv2, :pfc ], suffix: true
  enum :pay_grade, [ :e1, :e2, :e3 ], prefix: :grade
end

member.pfc_rank! # equivalent to member.rank = :pfc
member.pfc_rank? # => true

member.grade_e3!
member.grade_e1? # => false

If you don’t need the instance methods for an enum, you can disable them by setting instance_methods: false.

class Member < ApplicationRecord
  enum :rank, [ :pvt, :pv2, :pfc ], instance_methods: false
end

More details in the API docs at https://api.rubyonrails.org/v8.0.0/classes/ActiveRecord/Enum.html.

2 Likes