Rails:ActiveRecord 在设置随机布尔属性时验证失败 [英] Rails: Validation fails for ActiveRecord in setting a random Boolean Attribute

查看:49
本文介绍了Rails:ActiveRecord 在设置随机布尔属性时验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过播种将布尔值保存在模型中

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

如果我使用

dutyStatus.active = [false,true].sample

这不会在数据库中记录任何内容.0,1 或真"、假"也不是;除非我确实喜欢隐式 true,否则它会保存值 1;但我需要随机布尔值.这是错误:

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?

推荐答案

如果将 active 设置为 lambda 对象,然后在设置值时调用它会怎样?

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

试试这个:

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

我认为它也与验证布尔字段的存在有关.我认为您应该验证是否包含 active:

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

这篇关于Rails:ActiveRecord 在设置随机布尔属性时验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆