2016-09-26 47 views
1

我想創建一個記錄,如果不存在。Rails驗證失敗,並在控制器中創建。

@construction = Construction.create!(:bom_created => false, 
            :recipe_created => false, 
            :cost_rollup_complete => false, 
            :opportunity_id => $current_opportunity) 

bom_created,recipe_created和cost_rollup_complete是每個模型的必填字段。

validates_presence_of :bom_created 
validates_presence_of :recipe_created 
validates_presence_of :cost_rollup_complete 

我以爲我是好與傳遞的價值觀的創造的一部分,但我得到

ActiveRecord::RecordInvalid in ConstructionsController#show 
Validation failed: Bom created can't be blank, Recipe created can't be blank, Cost rollup complete can't be blank 

Rails.root: C:/Users/cmendla/RubymineProjects/product_development 

Application Trace | Framework Trace | Full Trace 
app/controllers/constructions_controller.rb:76:in `show' 
Request 

Parameters: 

{"id"=>"1"} 
+0

是你的領域布爾?如果是這樣的話,這是http://stackoverflow.com/a/10506648/1536309 –

回答

3

validates_presence_of會返回無效的false。 (false.present? => false

您應該改用

validates_inclusion_of :bom_created, in: [true, false] 
validates_inclusion_of :recipe_created, in: [true, false] 
validates_inclusion_of :cost_rollup_complete, in: [true, false] 
+1

的副本在rails中,'present?'被定義爲'!blank?'它是同樣的東西。資料來源:http://api.rubyonrails.org/classes/Object.html#method-i-present-3F – BananaNeil

3

如果你想驗證布爾場(其中實際值是true和false)的情況下,你將要使用validates_inclusion_of :field_name,in:[true,false]。

改變你的驗證來

validates_inclusion_of :bom_created,   in: [true, false] 
validates_inclusion_of :recipe_created,  in: [true, false] 
validates_inclusion_of :cost_rollup_complete, in: [true, false] 

source