2017-12-18 352 views
2

我创建了一个模型Tester,整数列为tester_type,并声明模型中的enum变量。Rails - 使用ActiveRecord :: Enum的参数错误

class Tester < ApplicationRecord 
    enum tester_type: { junior: 0, senior: 1, group: 2 } 
end 

我得到以下错误,而试图创建/初始化该模型中的对象:

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.

所以,我试图改变tester_typetype_of_tester但它抛出同样的错误:

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.

我已经搜索的解决方案,我发现这个错误是一个常数ENUM_CONFLICT_MESSAGEActiveRecord::Enum类,但不能够找到这个问题的原因。

请帮帮我。

谢谢。

+0

更改emum的名称,不要使用testers_type这已被rails使用。 – Sunny

+0

我试着将它改为'type_of_tester',但是它抛出了相同的错误。 –

+0

你也可以粘贴该错误。 – Sunny

回答

2

在这种情况下,如果你想使用枚举,你最好将你的标签重命名为其他东西。这不仅限于枚举 - 许多Active Record功能为您生成方法,通常也没有办法选择退出这些生成的方法。

然后更改groupanother_name

还是应该遵循这也

enum :kind, [:junior, :senior, :group], prefix: :kind 
band.kind_group? 
1

检查了这一点。它是您遇到问题的选项组。您可以使用前缀选项,因为在这个岗位

enum options

1

提到可以使用:_prefix:_suffix选择,当你需要定义具有相同的价值观或你的情况多枚举,以避免与已定义的方法发生冲突。如果传递值为true,则方法前缀/后缀为枚举的名称。另外,也可以提供一个自定义的值:

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 

然后你就可以使用这些范围为:

tester.type_group! 
tester.type_group? # => true 

Tester.type_group # SELECT "testers".* FROM "testers" WHERE "testers"."tester_type" = $1 [["tester_type", 2]] 
# or, 
Tester.where(tester_type: :group) # SELECT "testers".* FROM "testers" WHERE "testers"."tester_type" = $1 [["tester_type", 2]] 
相关问题