Ruby on Rails,jquery不为模型赋值



我在Ruby on Rails应用程序中具有基本形式。其中一个字段是根据其他字段计算的。如果验证失败,并且呈现new操作,则蒸发计算值。

class Model < ApplicationRecord
end

这是我的控制器:

class ModelsController < ApplicationController
    def create
        @model = Model.new(secure_params)
        if @model.save
          redirect_to @model
        else
          render 'new'
        end
    end
    def secure_params
       params.require(:model).permit(:count,:unitPrice,:totalPrice);                            
    end
end

这是new.html.erb表格:

<%= form_with model: @model, local: true do |form| %>
    <p>
      <%= form.label :count %><br>
      <%= form.number_field :count, id:'count' %>
    </p>
    <p>
      <%= form.label :unitPrice %><br>
      <%= form.number_field :unitPrice, id:'unitPrice' %>
    </p>
    <p>
      <%= form.label :totalPrice %><br>
      <%= form.number_field :totalPrice, id:'totalPrice' %>
    </p>
    <p>
      <%= form.submit %>
    </p>
<% end %>
<script>
  function calculateTotalPrice(){
     var count=$("#count").val();
     var unitPrice=$("#unitPrice").val();
     if(unitPrice && count ){
        var totalPrice=parseFloat(unitPrice*count).toFixed(2);
        $("#totalPrice").val(totalPrice); 
     }
  }
  $(document).ready(function(){
      $("#count").bind('keyup mouseup',calculateTotalPrice);
      $("#unitPrice").bind('keyup mouseup',calculateTotalPrice);
  });
</script>

当我提交表格时,如果验证还可以,则没有问题。但是,如果模型有误差,则从模型中删除了总价。我认为插入总价字段的值未注入Ruby模型。

我缺少什么?

谢谢。

jQuery看起来不错。

可以阻止它,因为默认情况下,数字输入仅接受整数值。将参数步骤设置为"任何"将允许十进制值。尝试:

<%= form.number_field :totalPrice, id:'totalPrice', step: :any %>

另外,请仔细检查整数字段是否在模型中不是类型的整数,而是浮动或小数。

最新更新