我已經添加了state_machine支持我的Post類:紅寶石state_machine寶石 - 測試validates_presence_of
state_machine :state, :initial => :draft do
event :publish do
transition :draft => :published
end
state :draft do
end
state :published do
end
end
在ERB,新郵表明它可以發佈:
>> k=Job.new => #<Job id: nil, title: nil> >> k.can_publish? => true
但是,它實際上不能發佈:
>> k.publish! StateMachine::InvalidTransition: Cannot transition state via :publish from :draft
事實證明,類validates_presence_of:title阻止了狀態的改變。 save!()方法失敗,因爲:title是必需的。不幸的是,InvalidTransition錯誤有點欺騙性。
我擔心這個錯誤信息會干擾View層對丟失字段(在我的例子中爲title)的處理。有沒有辦法在can_publish中測試validates_presence_of?方法?
**編輯**
我發現的StateMachine ::機文檔中的以下內容:?
can_park(需求= {}) - 檢查是否 「公園」 事件可以被解僱給出對象的當前狀態。這不會在ORM 集成中運行驗證。要檢查事件是否可以觸發並通過驗證, 將使用事件屬性(例如state_event),如每個ORM集成的 「Events」文檔中所述。
現在,如果我可以確定哪些'使用事件屬性(例如state_event),如每個ORM集成的「Events」文檔中所述。意味着在ActiveRecord的範圍內。