Having a rfq model in the app. There are two fields. One is need_report which is a boolean. Another one is report_language which is a string. The logic is if need_report is true, then there should be an entry in report_language. Otherwise, if need_report if false, report_language could be empty. Here is the code in rfq.rb:
validates :need_report, :presence => true
validates_inclusion_of :need_report, :in => [true, false]
validates :report_language, :presence => {:if => :need_report?}
def need_report?
need_report
end
However the following rspec case failed:
it "should be OK for nil report_language if need_report is false" do
rfq = Factory.build(:rfq, :need_report => false, :report_language => nil)
rfq.should be_valid
end
The error is that the rfq is not valid:
1) Rfq should be OK for nil report_language if need_report is false
Failure/Error: rfq.should be_valid
expected valid? to return true, got false
# ./spec/models/rfq_spec.rb:57:in `block (2 levels) in <top (required)>'
This case could pass if “validates :need_report, :presence => true” is removed from the model. It seems that if need_report is true, then report_language can not be empty.
Any thoughts about the problem? Thanks.
You can’t use
validates_presence_oforvalidates :column, :presence => trueto check if boolean columns are empty.http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_presence_of
Answer: Instead you need to use
validates_inclusion_ofand specify an array of accepted inputs, which you already have. This should be sufficient validation for what you want to do.Explanation: Your first validation is seeing
falsein the column (which, in Ruby is equivalent tonil). It then runs.blank?onniland gets backtrue(false == nil&nil.blank? == true), meaning it thinks the column is blank and it throws an error.