2017-06-19 67 views
0

我有限定enum像這樣一個模型:ActiveRecord的枚舉和髒屬性

enum status: [ :init, :requested, :packed, :paid, :shipped ]

我也有其使用髒屬性下面的方法。

def shipment_requested 
    status_changed?(from: :init, to: :requested) 
    end 

    def shipment_packed 
    status_changed?(from: :requested, to: :packed) 
    end 

    def shipment_paid 
    status_changed?(from: :packed, to: :paid) 
    end 

    def shipment_shipped 
    status_changed?(from: :paid, to: :shipped) 
    end 

有很多模型回調依賴於此,如更新時間戳和發送電子郵件。

但不幸的是沒有這個作品。

sh = Shipment.find(1) 
sh.init? 
=> true 
sh.requested! 
sh.requested? 
=> true 
sh.shipment_requested 
=> false 

上述代碼有什麼問題?這是一個錯誤?

我可以在控制器手動設置所有的值,但這種違背了使用其自帶的相當不錯的功能,按照上面的文檔枚舉的目的,類似定義範圍和方法來檢查status

+0

什麼是'status_changed?'? – Pavan

+1

[AASM](https://github.com/aasm/aasm)正是爲這種情況而設計的。 – 31piy

+1

@Pavan [rails dirty屬性](http://api.rubyonrails.org/classes/ActiveModel/Dirty.html) – static

回答

2

嘗試將值作爲字符串發送到changed?方法:

class Entry < ApplicationRecord 
    enum type: [:single, :double, :triple] 
end 

e = Entry.first 
e.type # => "single" 
e.type = :double 
# notice here values are strings, not symbols 
e.type_change # => ["single", "double"] 
e.type_changed?(from: :single, to: :double) # => false 
e.type_changed?(from: "single", to: "double") # => true 
+0

謝謝!有沒有一種方法可以避免在模型髒屬性方法中硬編碼字符串文字? – static

+0

那麼,我是怎麼錯過這個的? :) 好一個! – Pavan

+1

@static我只知道如何刪除字符串的新值:'e.type_was ==「single」&& e.double?' –