2014-08-31 106 views
6

這是我第一次使用枚舉與軌道4,我遇到了一些問題,有幾個考慮骯髒的解決方案,並要檢查是否有到位任何更優雅的解決方案:軌道4枚舉驗證

這是我的表遷移相關部分:

create_table :shippings do |t| 
    t.column :status, :integer, default: 0 
end 

我的模型:

class Shipping < ActiveRecord::Base 
    enum status: { initial_status: 0, frozen: 1, processed: 2 } 
end 

而且我在我看來此位(使用簡單的表單):

= f.input :status, :as => :select, :collection => Shipping.statuses, :required => true, :prompt => 'Please select', label: false 

所以在我的控制器:

def create 
    @shipping = Shipping.create!(shipping_params) 

    if @shipping.new_record? 
     return render 'new' 
    end 

    flash[:success] = 'Shipping saved successfully' 
    redirect_to home_path 
    end 

private 

    def shipping_params 
    params.require(:shipping).permit(... :status) 
    end 

所以,當我提出創建表單和創建行動火我得到這個驗證錯誤:

'1' is not a valid status 

所以我想我知道問題是數據類型,所以我在模型中添加了這一點:

before_validation :set_status_type 

    def set_status_type 
    self.status = status.to_i 
    end 

但是這似乎沒有做任何事情,我該如何解決這個問題?有沒有人有類似的經歷?

回答

3

你可以找到解決方案here

基本上,您需要傳遞字符串('initial_status','frozen'或'processed'),而不是整數。換句話說,你的表格必須是這樣的:

<select ...><option value="frozen">frozen</option>...</select> 

你可以在你的形式做statuses.keys實現這一目標。另外(我相信)你不需要before_validation

或者,您可以添加一個驗證這樣的:

validates_inclusion_of :status, in: Shipping.statuses.keys 

不過,我不知道這驗證是有道理的,因爲要轉讓的無效值狀態提出了一個ArgumentError(see this)。