ruby-on-railsruby-on-rails-4rails-activerecordrails-modelsseeding

Rails: Validation fails for ActiveRecord in setting a random Boolean Attribute


I am trying to save a boolean value in a model by seeding it

20151130014042_create_duty_statuses.rb

class CreateDutyStatuses < ActiveRecord::Migration
  def change
    create_table :duty_statuses, :id => false  do |t|
      t.string :id, limit: 36, primary: true, null: false
      t.string :remark, :limit => 256
      t.boolean :active, :required => true, default: false
      t.string :employee_id,limit: 36, :required => true
      t.timestamps null: false
    end
  end
end

duty_status.rb

class DutyStatus < ActiveRecord::Base
  include UUIDHelper
  belongs_to :employee
  validates_length_of :remark , maximum: 256, message: "description must be less than 256 characters"
  validates_presence_of :active
end

seeds.rb

 dutyStatus = DutyStatus.new(remark: Faker::Lorem.sentence, employee: myEmployee)
 dutyStatus.active = [false,true].sample
 dutyStatus.created_at = rand(720..72000).hours.ago
 dutyStatus.save

If I use

dutyStatus.active = [false,true].sample

This does not record anything in the database. neither does 0,1 or "true", "false"; unless I do like an implicit true, it saves the value 1; but I need random boolean values. Here's the error:

ActiveRecord::RecordInvalid: Validation failed: Active can't be blank

How do I save random values in the model?


Solution

  • What if you set the active as a lambda object and then call it on setting value?

    Try this out:

    active = -> { [false,true].sample }
    dutyStatus = DutyStatus.new(remark: Faker::Lorem.sentence, employee: myEmployee)
    dutyStatus.active = active.call
    dutyStatus.created_at = rand(720..72000).hours.ago
    dutyStatus.save
    

    I think it also has something to do with validating the presence of boolean field. I think you should validate the inclusion of active:

    validates :active, inclusion: { in: [true, false] }