1

I am trying to create a record if none exists.

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

bom_created, recipe_created and cost_rollup_complete are mandatory fields per my model.

validates_presence_of :bom_created
validates_presence_of :recipe_created
validates_presence_of :cost_rollup_complete

I thought I was Ok with passing the values as part of the create but I am getting

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"}
Chris Mendla
  • 987
  • 2
  • 10
  • 25

2 Answers2

3

validates_presence_of will return invalid for false. (false.present? => false)

You should instead use

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]
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
BananaNeil
  • 10,322
  • 7
  • 46
  • 66
  • 1
    In rails, `present?` is defined as `!blank?` its the same thing. Source: http://api.rubyonrails.org/classes/Object.html#method-i-present-3F – BananaNeil Sep 26 '16 at 21:03
3

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].

change your validations to

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

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114