[英]Override migration default value in Rails form input field
I am having a products table with default min_quantity is 0 and max_quantity is MAX INT number 999999999 .我有一个产品表,默认min_quantity为0 , max_quantity为 MAX INT number 999999999 。 When I tried to display this form, the default values from backened are displayed in the UI with min_quantity as 0 and max_quantity as 999999999. How to leave this input fields as blank for the create action?当我尝试显示此表单时,来自 backened 的默认值显示在 UI 中,其中 min_quantity 为 0,max_quantity 为 999999999。如何将此输入字段留空以进行创建操作?
schema.rb:架构.rb:
create_table "products”, id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", force: :cascade do |t|
t.string "name", null: false
t.integer "min_quantity”, default: 0, null: false
t.integer "max_quantity”, default: 999999999, null: false
end
products/_form.slim:产品/_form.slim:
= simple_form_for([@product]) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :min_quantity, label: 'Minimum Quantity'
= f.input :max_quantity, label: 'Maximum Quantity'
I tried using value: nil
as:我尝试使用value: nil
作为:
-if f.object.new_record?
= f.input :min_quantity, label: 'Minimum Quantity’, input_html: {value: nil}
-else
= f.input :min_quantity, label: 'Minimum Quantity'
But when there is validation error, the values entered are getting disappeared.但是当出现验证错误时,输入的值会消失。 The same issue when I use jQuery.当我使用 jQuery 时同样的问题。
So how can I handle this issue of overriding blackened values in Rails?那么我该如何处理在 Rails 中覆盖变黑值的问题呢? Please help请帮忙
You can get the behavior you want by setting the min_quantity
and max_quantity
to nil
in the new
method of the controller.您可以通过在 controller 的new
方法min_quantity
和max_quantity
设置为nil
来获得您想要的行为。
def new
@product.min_quantity = @product.max_quantity = nil
end
The reason why the values of min_quantity
and max_quantity
are show when the validation fails is because they are set in the @product
object so they actual values of the attributes are going to be shown when the form is reloaded验证失败时显示min_quantity
和max_quantity
的值的原因是因为它们是在@product
object 中设置的,因此它们的实际属性值将在重新加载表单时显示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.