【发布时间】: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