我写了一个rails表单,它工作正常,直到我添加了一个javascript。此javascript汇总了用户输入的字段值,并将其保存在总字段中,因此用户无需手动累计它。
这是我的代码:
<script type="text/javascript">
function findTotal(){
console.log("this is working")
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
<%= bootstrap_form_for(@payment) do |f| %>
<div class="field">
<%= f.text_field :student_id,label: "Admission Number of Student" %>
</div>
<div class="field">
<%= f.number_field :tuition_fee , onblur: "findTotal()", id: "qty1", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :fine, onblur: "findTotal()", id: "qty2", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :previous_books, onblur: "findTotal()", id: "qty3", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :annual_fund, onblur: "findTotal()", id: "qty4", name: "qty" %>
</div>
<div class="field">
<%= f.hidden_field :total, name: "total", id: "total" %>
</div>
<div class="actions">
<%= f.submit class: "btn btn-success" %>
</div>
<% end %>
现在,当我填写表单时,该功能正常工作,并且提交按钮也会创建记录,但在这些数字字段中输入的所有值都不会存储在数据库中,并且显示为nil。如果我从数字字段中删除它,这些工作正常。知道我做错了什么吗?谢谢。 编辑: 这是我的参数:
private
# Use callbacks to share common setup or constraints between actions.
def set_payment
@payment = Payment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def payment_params
params.require(:payment).permit(:student_id, :section_id, :year, :month, :date, :payment_mode, :tuition_fee, :fine, :previous_books, :annual_fund, :total)
end
end
和相关的控制器方法:
def create
@payment = Payment.new(payment_params)
@payment.student_id = Student.find_by_admission_number(@payment.student_id).id
@payment.section_id = Student.find(@payment.student_id).section_id
respond_to do |format|
if @payment.save
format.html { redirect_to new_payment_path, notice: 'Payment Record was successfully created.' }
format.json { render :show, status: :created, location: @payment }
else
format.html { render :new }
format.json { render json: @payment.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
问题是您要覆盖'name'属性。它们应该像,例如:name="payment[fines]"
。因此,当您提交时,它会生成以下对象:
Parameters=> { payment => { fines: value} }
这是在您的控制器(payment_params)
中指出的