2

我正在使用 Virtus gem 并尝试将字符串自动转换为布尔值,但没有成功......如果你能看到这段代码有什么问题......

Virtus.coercer do |config|
  config.string.boolean_map = { 'true' => true, 'false' => false }
end

class BookingWizard
  include Virtus

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attribute :know_doctor, Boolean, default: false
end

1.9.3 (main):0 > b = BookingWizard.new
=> #<BookingWizard:0x007fea748bf338
 @know_doctor=false>
1.9.3 (main):0 > b.know_doctor = "true"
=> "true"
1.9.3 (main):0 > b.know_doctor
=> "true"
1.9.3 (main):0 > b.know_doctor.class
=> String
1.9.3 (main):0 > Virtus.coercer[String].to_boolean("true")
=> true
4

1 回答 1

0

如果您已经定义了一个类,请尝试使用Axiom::Types::Boolean而不是。BooleanBoolean

class BookingWizard
  include Virtus

  attribute :know_doctor, Axiom::Types::Boolean, default: false
end

如果这行得通,你可能有一个::Boolean在 Virtus 之前被发现的类。用于撬开你的show-source Boolean班级。Boolean

于 2019-08-01T14:15:51.430 回答