The error "You tried to define an enum named "stage" on the model "Challenge", but..." occurs when rails define an enum in the model.

Asked 2 years ago, Updated 2 years ago, 138 views

You want to define the following enum in the model:

class Model < ActiveRecord::Base
  enum stage: {member_only: 0, public: 1, demo: 2}

The following error occurs:

You tried to define an enum named "stage" on the model "@@@@", but this will generate a class method "public", which is already defined by Active Record.

Why is that?

ruby-on-rails enum model

2022-09-22 21:12

1 Answers

It's a self-answer.

When you create enum in the model, a method is created under each name of enum as shown below.

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

# # conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status  # => "active"

# # conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status    # => "archived"

Source

So if you're already using a different method name, you can't use it in enum.


2022-09-22 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.