State Machine, Model Validations and RSpec

后端 未结 1 846
深忆病人
深忆病人 2021-01-06 02:47

Here\'s my current class definition and spec:

class Event < ActiveRecord::Base

  # ...

  state_machine :initial => :not_started do

    event :game_s         


        
相关标签:
1条回答
  • 2021-01-06 03:15

    It looks like you're running into a caveat noted in the documentation:

    One important caveat here is that, due to a constraint in ActiveModel's validation framework, custom validators will not work as expected when defined to run in multiple states. For example:

     class Vehicle
       include ActiveModel::Validations
    
       state_machine do
         ...
         state :first_gear, :second_gear do
           validate :speed_is_legal
         end
       end
     end
    

    In this case, the :speed_is_legal validation will only get run for the :second_gear state. To avoid this, you can define your custom validation like so:

     class Vehicle
       include ActiveModel::Validations
    
       state_machine do
         ...
         state :first_gear, :second_gear do
           validate {|vehicle| vehicle.speed_is_legal}
         end
       end
     end
    
    0 讨论(0)
提交回复
热议问题