Ruby on rails Rails:下拉列表中的值始终为零
我的表单包含两个输入折扣的选项Ruby on rails Rails:下拉列表中的值始终为零,ruby-on-rails,Ruby On Rails,我的表单包含两个输入折扣的选项 通过下拉菜单,或 通过文本字段 下拉列表: <%= f.collection_select(:discount, Warehouse.where(product: sale.product), :discount, :discount, {prompt:true}, {class: 'form-control'}) %> <%= f.text_field :discount, class: "form-control", placehold
- 通过下拉菜单,或
- 通过文本字段
<%= f.collection_select(:discount, Warehouse.where(product: sale.product), :discount, :discount, {prompt:true}, {class: 'form-control'}) %>
<%= f.text_field :discount, class: "form-control", placeholder: "e.g. 99.00" %>
可以手动输入任何值
一些JavaScript魔术确保,一次只能看到其中一个表单字段。隐藏表单字段接收值“disabled”
我的问题是:只有当我提交文本字段(而不是下拉列表)时,才会保存正确的值。当我尝试从下拉列表中提交值时,它是nil
,无论我是将其保留为“请选择”还是99.00
这是我的模型:
class Sale < ActiveRecord::Base
before_create :calc_discount
def calc_discount
if discount.present?
discount = self.discount.strip.sub(',', '.').to_f
write_attribute(:discount, discount) unless destroyed?
else
discount = nil
write_attribute(:discount, discount) unless destroyed?
end
end
end
class Sale
我不明白为什么循环会通过第一个if子句,即使我从下拉列表中选择了一个值
您有什么想法吗?如果有两个表单字段具有相同的“name”属性,则位于dom下方的表单字段将覆盖上一个表单字段。这就是这里发生的事吗?text_字段是否覆盖了select?@MaxWilliams my JavaScript假装,当它不可见的字段被禁用时,表单将跳过它。您如何禁用它?您说过要将值设置为“disabled”-这实际上不会阻止它在params中发送。另一方面,如果您在其上设置了禁用属性,则会阻止其在参数中发送。它实际上在我使用的其他表单上工作,所以这不会是问题:
是的,这是禁用的属性,我说这会阻止它通过params:)你的问题不清楚你在做什么。