2013-08-26 76 views
2

行爲我有兩個型號ProductStatus如何在產品HAS_ONE狀態和狀態機的關聯

在產品型號的情況下添加種子數據RSpec的測試中,我有

class Product < ActiveRecord::Base 
    attr_accessible :image_url, :name, :status_id 

    belongs_to :status 


    state_machine :status_id, :initial => :dead do 

    event :activate do 
     transition all => :active 
    end 

    event :de_activate do 
     transition all => :dead 
    end 

    event :set_out_of_stock do 
     transition all => :out_of_stock 
    end 


    state :active, :value => Status.where(:code=>"ACTIVE").first.id 
    state :dead, :value => Status.where(:code=>"DEAD").first.id 
    state :out_of_stock, :value => Status.where(:code=>"OUT_OF_STOCK").first.id 
    end 

end 

而運行rspec,它會嘗試首先加載產品模型,並給出錯誤說明nil.id是4等....因爲狀態未被填充。

如何在加載模型之前預加載狀態數據?

回答

0

我懷疑這是最佳解決方案,但您可以將狀態機初始化(即state_machine方法調用)置於Product的Class方法中,並在填充Status後明確調用該方法。我測試過這個,它似乎工作正常。