I have created a model Tester
with integer column tester_type
and declared enum variable in the model.
class Tester < ApplicationRecord
enum tester_type: { junior: 0, senior: 1, group: 2 }
end
I am getting below error while trying to create / initialize an object for that model:
ArgumentError: You tried to define an enum named "tester_type" on the model "Tester", but this will generate a class method "group", which is already defined by Active Record.
So, I tried changing tester_type
to type_of_tester
but it throws same error:
ArgumentError: You tried to define an enum named "type_of_tester" on the model "Tester", but this will generate a class method "group", which is already defined by Active Record.
I have searched for the solution and I found this error was a constant ENUM_CONFLICT_MESSAGE
in ActiveRecord::Enum class but, cannot able to find the cause of this problem.
Please help me.
Thanks.
答案 0 :(得分:2)
In this case, if you want to use enum, you are probably better off renaming your label to something else. This is not unique to enums – a lot of Active Record features generates methods for you and usually there aren't ways to opt-out of those generated methods.
then change table = BridgeTable.objects.get(pk='1')
print(table.seats.north)
to group
OR you should follow this also
another_name
答案 1 :(得分:1)
check this out. it is the option group you are having a problem with. You can use prefix option as mentioned in this post
答案 2 :(得分:1)
当您需要定义具有相同值的多个枚举时,或者在您的情况下,可以使用function Square() {
}
// here other constructors for Circle and Triangle
var factory = {
"Square": Square,
"Circle": Circle,
"Triangle" : Triangle
}
var typeName;
// here some code which sets typeName
var typeObj = new factory[typeName]();
或:_prefix
选项,以避免与已定义的方法冲突。如果传递的值为:_suffix
,则方法的前缀/后缀为枚举的名称。也可以提供自定义值:
true
通过上面的例子,bang和谓词方法以及相关的范围现在都是相应的前缀和/或后缀:
class Conversation < ActiveRecord::Base
enum status: [:active, :archived], _suffix: true
enum comments_status: [:active, :inactive], _prefix: :comments
end
对于你的情况,我的建议是使用类似的东西:
conversation.active_status!
conversation.archived_status? # => false
conversation.comments_inactive!
conversation.comments_active? # => false
然后您可以将这些范围用作:
class Tester < ApplicationRecord
enum tester_type: { junior: 0, senior: 1, group: 2 }, _prefix: :type
end
答案 3 :(得分:1)
指定前缀选项对我有用。
# models/tester.rb
enum tester_type: { junior: 0, senior: 1, group: 2 }, _prefix: true
然后使用它:
Tester.first.tester_type
=> nil
Tester.first.tester_type_junior!
=> true
Tester.first.tester_type
=> 0
请注意,可以使用问题中提供的相同符号为枚举值指定显式字符串值而不是整数。这使得保存的 db 值更具可读性。
enum tester_type: { junior: 'junior', senior: 'senior', group: 'group' }, _prefix: true
Tester.first.tester_type_senior!
=> true
Tester.first.tester_typey