3

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?

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
james
  • 515
  • 4
  • 14

2 Answers2

2

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] }
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • nope still getting ActiveRecord::RecordInvalid: Validation failed: Active can't be blank – james Dec 08 '15 at 22:44
  • @James, Ok, I think you should validate the inclusion of active (feels like I had similar issue with boolean field some time ago). `validates :active, inclusion: { in: [true, false] }`. Try it out – Andrey Deineko Dec 08 '15 at 22:51
2

Andrey Deineko's answer was very helpful. Just to add to it.

I had a boolean field that I was trying to validate in my Rails 6 application using

validates :affiliate_status, presence: true

But it was failing. I was getting the error:

{
    "affiliate_status": [
        "can't be blank"
    ]
}

Here's how I solved it:

I had to change the validation from:

validates :affiliate_status, presence: true

to:

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

That's all.

I hope this helps

Promise Preston
  • 24,334
  • 12
  • 145
  • 143