Ruby on Railsアプリケーションには基本的なフォームがあります。フィールドの1つは他のフィールドに従って計算されます。検証が失敗し、new
アクションがレンダリングされると、計算された値が蒸発します。Ruby on Rails、jqueryはモデルに値を割り当てません
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>
私がフォームを送信すると、検証がOKであれば、問題はありません。しかし、モデルにエラーがある場合、totalPrice値はモデルから削除されます。私はtotalPriceフィールドに挿入された値がRubyモデルに注入されないと思います。
私には何が欠けていますか?
ありがとうございました。
unitPriceとcountが文字列である場合、この部分はあなたにとって奇妙に見えますか? 'parseFloat(unitPrice * count)' – Taplar
私はparseFloat()を削除しましたが、何も変更されていません –