Why does false invalidate validates_presence_of?

前端 未结 2 464
陌清茗
陌清茗 2020-12-13 23:18

Ok steps to reproduce this:

prompt> rails test_app
prompt> cd test_app
prompt> script/generate model event_service published:boolean
相关标签:
2条回答
  • 2020-12-13 23:54

    See the API docs...

    If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false].

    0 讨论(0)
  • 2020-12-13 23:59
    validates_inclusion_of :your_field, :in => [true, false]
    

    no longer works for some versions after 1.3.0 of the shoulda matchers when you are testing that only Boolean values are accepted by your model.

    Instead, you should do something like this:

    it { should allow_value(true).for(:your_field) }  
    it { should allow_value(false).for(:your_field) }
    it { should_not allow_value(nil).for(:your_field) }
    

    You can see the discussion here.

    There was a partial fix for this that now warns if you are trying to do this here

    0 讨论(0)
提交回复
热议问题