【问题标题】:Save a form input with the result of two others forms inputs of the same form in Rails将表单输入与 Rails 中相同表单的其他两个表单输入的结果一起保存
【发布时间】:2020-04-02 16:06:21
【问题描述】:

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

我用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


    【解决方案1】:

    这是你可以在前端使用 JavaScript 或在后端使用 Rails 做的事情

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

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

    # 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
    

    这只是伪代码,但我希望它能让您很好地了解如何完成它。测试一下(它需要一些调整)——应该可以。

    希望有帮助:)

    【讨论】:

      【解决方案2】:

      @Patrick 感谢您给我正确的方法,但我无法让它工作,即使是原始的 q1 v1 也只需保存空白字段,最后这段代码对我有用

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

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 2019-06-18
        • 2014-06-27
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2022-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多