将表单输入与其他两个表单的结果保存在Rails中

问题描述 投票:0回答:2

我有一个带有描述,数量和单位成本的表格(简单表格)。

我使用JS显示每一行的小计和总计,只为用户可以看到总计。

我的问题是,我想将表单总计保存在相同表单中的输入中,也许这不是最好的方法,但我需要这样做。

输入“总计”与其他输入的结果数(q1 * v1)+(q2 * v2)一起保存,创建表格时我不需要实时显示以保存它

<%= f.input :v1%> <!-- value of item 1 -->
<%= f.input :q1%> <!-- quantity of item 1 -->

<%= f.input :v2%> <!-- value of item 2 -->
<%= f.input :q2%> <!-- quantity of item 2 -->     

<%= f.input :total %> <!-- here i need to automaticle save the
 value of (v1*q1)+(v2*q2) when I hit the submit(create) button-->

      
ruby-on-rails ruby postgresql forms simple-form
2个回答
0
投票

这是您可以在前端使用JavaScript或在后端使用Rails进行的操作

((我假设您要在后端执行此操作,因为您说的只是正确地[[saves才重要。)] >>为此,您需要在before_save回调中将此逻辑放入ActiveRecord模型中(通常,逻辑不应该进入Controller中。)>

# app/controllers/my_models_controller.rb class MyModelsController < ApplicationController def update @model = MyModel.new(my_model_params) if @model.save # It worked else # It failed end end private def set_model #... end def my_model_params params.permit(:v1,v2,q1,q2) end end # app/models/my_model.rb class MyModel attr_accessor :v1 attr_accessor :v2 attr_accessor :q1 attr_accessor :q2 before_save :calculate_total private def calculate_total @total = (v1*q1)+(v2*q2) end end

这只是伪代码,但我希望它为您提供了如何完成此操作的好方法。测试一下(它需要一些调整)-应该可以。

希望有所帮助:)

@@ Patrick谢谢您给我正确的方法,但是我无法使其正常工作,只需保存空白字段,甚至是原始的q1 v1,最后此代码对我也可以工作

before_save do self.total = (self.q1 * self.v1) * (self.q2 * self.v2) end

0
投票
@@ Patrick谢谢您给我正确的方法,但是我无法使其正常工作,只需保存空白字段,甚至是原始的q1 v1,最后此代码对我也可以工作
© www.soinside.com 2019 - 2024. All rights reserved.