2015-01-16 89 views
0

我有這樣的簡化模型:Rails的模型DEFAULT_VALUE法衝突

class Contract < ActiveRecord::Base 

    belongs_to :user belongs_to :plan 

    before_validation :set_default_is_voided 
    before_validation :set_default_expiration 

    validates :user, presence: true 
    validates :plan, presence: true 
    validates :contract_date, presence: true 
    validates :is_voided, presence: true 
    validates :expiration, presence: true 

    protected 

    def set_default_is_voided 
    if self.is_voided.nil? 
     self.is_voided = false 
     ap self.is_voided.present? 
     ap self.is_voided 
    end 
    end 

    def set_default_expiration 
    if self.contract_date.present? 
     self.expiration = self.contract_date+1.month 
    end 
    end 

end 

這rspec的簡化測試:

context "Should create default values" do 
    it "Have to create is_voided" do 
    user = FactoryGirl.create(:user) 
    plan = FactoryGirl.create(:planContract) 
    ap "HERE" 
    contractDefault = FactoryGirl.create(:contractDefault, plan: plan, user: user) 
    ap contractDefault 
    expect(contractDefault.is_voided).to eq(false) 
    end 
    it "Have to create expiration" do 
    #expect(contract.expiration).should eq(Date.today()+1.month) 
    end 
end 

FactoryGirl:

FactoryGirl.define do 
    factory :contractVoid, class:Contract do 
    end 
    factory :contractDefault, class:Contract do 
    contract_date Date.today 
    end 
end 

這個測試失敗, 'is_voided不能爲空'。

問題是: 爲什麼before_validation中的方法「set_default_is_voided」不通過presence true驗證?此外,self.is_voided.present?返回false,它爲什麼會發抖?

回答

1

你回答了你自己的問題,爲什麼set_default_is_voided未通過的presence: true驗證,即self.is_voided.present?回報false,這是多麼presence: true確定。

self.is_voided.present?回報false因爲false.present? == falseA concise explanation of nil v. empty v. blank in Ruby on Rails

單程見Rails: how do I validate that something is a boolean?來驗證一個布爾字段不nil

請參閱http://www.quora.com/Why-does-Rails-make-false-blank-true關於Q & A關於blank?定義背後的動機。