2013-10-29 62 views
2

我正在使用Rails 4應用程序,並且我已經開始使用brainspec/enumerize gem。我在數據庫中有一個整數值,列status,並希望枚舉它在我的模型中。brainspec/enumerize拋出mysql默認值錯誤

下面你可以看到我用來設置它的代碼片段。不幸的是,在我的測試中(這些測試都是先前通過的),它抱怨由於無法保存行而創建Partner。無法指定默認狀態NULL。由於數據庫本身(MySQL)的缺省值設置爲0,並且從下面可以看出,後端側指示缺省值爲4:incomplete,因此不知道它從哪裏得到NULL

enumerize :status, in: [ 
    :pending, # 0 account has a pending billing request (but is not yet open) 
    :active,  # 1 account has an active base subscription 
    :suspended, # 2 account has been suspended (e.g. after a base subscription decline) 
    :expired, # 3 base subscription has expired 
    :incomplete, # 4 partner application process incomplete 
    :closed,  # 5 account has been permanently closed 
    :cancelled # 6 account has been cancelled by user (but is still unexpired) 
], default: :incomplete 

這裏是ActiveRecord/MySQL錯誤。

PartnerTest#test_create_with_nested_attributes: 
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'status' cannot be null: UPDATE `partner` SET `primary_contact_id` = 3, `status` = NULL WHERE `partner`.`id` = 3 
    test/models/partner_test.rb:9:in `block in <class:PartnerTest>' 

而且,我知道的默認值(:incomplete)是由Enumerize回升。如果我將亂碼放入默認值(default: :asdoiasoas),它會中斷。

我使用主/分支,使之與導軌4

的Gemfile

gem 'enumerize', :github => 'brainspec/enumerize' 

回答

0

工作根據brainspec/enumerize README,你應該爲每個狀態提供一個整數值,如:

enumerize :status, in: { 
    pending: 0, # 0 account has a pending billing request (but is not yet open) 
    active: 1,  # 1 account has an active base subscription 
    suspended: 2, # 2 account has been suspended (e.g. after a base subscription decline) 
    expired: 3, # 3 base subscription has expired 
    incomplete: 4 # 4 partner application process incomplete 
       # And so on... 
}, default: :incomplete 

由於您只提供了密鑰但沒有提供值,因此將其設置爲nil/NULL。