我有两个模型 Product
和 Status
在产品模型中,我有
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 时,它首先尝试加载 Product 模型并给出错误提示 nil.id
是 4 等等....因为状态未填充。
如何在加载模型前预加载状态数据?
最佳答案
我怀疑这是最佳解决方案,但您可以将状态机初始化(即 state_machine
方法调用)放在 Product
的类方法中并调用该方法在您填充 Status
之后明确。我已经对此进行了测试,它似乎工作正常。
关于ruby-on-rails - Product has_one状态和状态机作用于association的场景下如何为rspec测试添加种子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18435324/