我在表上有一列,在创建新记录时可能会填充也可能不会填充。我们称之为它free_shipping_amount
及其类型integer
,它驻留在shipping_methods
表中。
我也有此ShippingMethods
模型支持的表单。因此,我不希望此字段显示为,0
因为它不为零,只是什么都没有。
我如何才能使此列为可选列,或者不是必需列,或者使之不是零,还是一个空字符串,因为它是整数。看似nil
,null
将无法正常工作。
我已经尝试了以下迁移,但都无法正常工作:
change_column :shipping_methods, :free_shipping_amount, :integer,
default: ""
change_column_null :shipping_methods, :free_shipping_amount, true
change_column :shipping_methods, :free_shipping_amount, :integer,
:default => nil
change_column_default(:shipping_methods, :free_shipping_amount, nil)
change_column :shipping_methods, :free_shipping_amount, :integer, null: true
然后我尝试了一下,但是随后我的模型支持的表单显示了0
我不想要的内容。
change_column_default(:shipping_methods, :free_shipping_amount, 0)
该表上的字段如下所示:
t.integer "free_shipping_amount"
问题是,如果不将某些内容传递给该字段,就无法将记录保存到该表中。
我使用如下所示的强参数:
def shipping_method_params
params.require(:shipping_method).permit(:free_shipping_amount)
#other values removed for brevity
end
当我这样创建时:
@shipping_shop = ShippingMethod.create(shipping_method_params)
记录未创建,并且事务被回滚。
哎呀,我在模型中有这个。
validates :free_shipping_amount, numericality: true
那么,如何在不传递该字段值的情况下保存该模型呢?还是我仍然可以验证数字?
我刚刚在这里找到它是我的模型被顶起来。我必须将其添加到验证中才能接受空白值。
validates :free_shipping_amount, numericality: {allow_blank: true}
感谢大家的时间,并指出正确的方向!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句