【问题标题】:Ruby on Rails, jquery doesn't assign value to modelRuby on Rails,jquery 不为模型赋值
【发布时间】:2017-12-07 22:02:52
【问题描述】:

我的 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>

当我提交表单时,如果验证正常,则没有问题。但如果模型有错误,则从模型中删除 totalPrice 值。我认为插入到 totalPrice 字段的值不会注入到 Ruby 模型中。

我错过了什么?

谢谢。

【问题讨论】:

  • 鉴于 unitPrice 和 count 是字符串,你觉得这部分很奇怪吗? parseFloat(unitPrice*count)
  • 我删除了 parseFloat(),没有任何改变

标签: jquery ruby-on-rails ruby activerecord


【解决方案1】:

jQuery 看起来不错。

它可能会被阻止,因为数字输入默认只接受整数值。将参数 step 设置为“any”将允许十进制值。试试:

&lt;%= form.number_field :totalPrice, id:'totalPrice', step: :any %&gt;

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

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多