2013-08-26 61 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后明确调用该方法。我测试过这个,它似乎工作正常。