Rails-使用ActivereCord :: Enum的论点



我已经创建了一个具有整数tester_type的模型Tester,并在模型中声明了枚举变量。

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

我在尝试为该模型创建/初始化对象时要低于错误:

参数:您试图在模型" tester"上定义一个名为" tester_type"的枚举,但这将生成类方法" group",该类方法已经由活动记录定义。

所以,我尝试将tester_type更改为type_of_tester,但会引发相同的错误:

参数:您尝试在模型" tester"上定义一个名为" type_of_tester"的枚举,但这将生成一个类方法" group",该类方法已经由Active Record定义。

我已经搜索了该解决方案,我发现此错误是ActivereCord :: enum class中的常数ENUM_CONFLICT_MESSAGE,但是,无法找到此问题的原因。

请帮助我。

谢谢。

在这种情况下,如果要使用枚举,最好将标签重命名为其他东西。这不是枚举所独有的 - 许多活动记录功能为您生成方法,通常没有方法可以退出这些生成的方法。

然后将group更改为another_name

否则您也应该关注此

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

当您需要定义具有相同值的多个枚举时,或者在您的情况下,可以使用:_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]]

检查一下。这是您遇到问题的选项组。您可以使用本文中提到的前缀选项

枚举选项

指定一个前缀选项对我有用。

# 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_type

最新更新