ActiveRecord在设置随机布尔属性时验证失败

时间:2015-12-08 10:07:50

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord rails-models seeding

我试图通过播种来保存模型中的布尔值

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或“真”,“假”;除非我喜欢隐含的真,否则它会保存值1;但我需要随机布尔值。这是错误:

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

如何在模型中保存随机值?

2 个答案:

答案 0 :(得分:1)

Andrey Deineko's answer 非常有帮助。只是为了添加它。

我有一个 boolean 字段,我试图在我的 Rails 6 应用程序中使用

进行验证
validates :affiliate_status, presence: true

但是失败了。我收到错误:

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

我是这样解决的

我不得不更改验证:

validates :affiliate_status, presence: true

到:

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

仅此而已。

我希望这会有所帮助

答案 1 :(得分:0)

如果将active设置为lambda对象,然后在设置值上调用它,该怎么办?

试试这个:

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

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