在 Rails 中保存具有相同表单的其他两个表单输入的结果的表单输入

Save a form input with the result of two others forms inputs of the same form in Rails

我有一个包含描述、数量和单一成本的表格(简单表格)。

我用JS显示每一行的小计和总计,只是为了让用户能看到总计。

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

输入"total"保存的是其他输入的结果数(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-->

      

这是您可以在前端使用 JavaScript 或在后端使用 Rails

执行的操作

(我假设您想在后端执行此操作,因为您说的只是 正确保存 才重要。)

为此,您需要在 before_save 回调中将此逻辑放入您的 ActiveRecord 模型中(逻辑通常不应进入您的控制器)。

# 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