2017-12-18 375 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]] 
相關問題