简体   繁体   中英

Rails 4.0.13 composed_of set default value when nil assigned

Using rails 4.0.13

Using

class Shipment < ActiveRecord::Base
    composed_of :weight, 
                  class_name: 'Weight',
                  mapping: [[wight_value, :value], [weight_unit, :unit]],
                  converter: :build
end

I need to assign some default value when shipment.weight = nil

PS : I don't want to allow nil value but if somehow by external input comes then I would like to assign Weight.new(0)

Note: tried with converter but it fails when nil is passed like converter:

Proc.new {|value| Weight.new(value || 0)}

使用to_i将nil值转换为整数,例如:

Proc.new {|value| value.blank? ? Weight.new(value.to_i) : Weight.new(value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM