【问题标题】:Store calculation in database using variables submitted in a form使用表单中提交的变量将计算存储在数据库中
【发布时间】:2014-07-09 17:47:17
【问题描述】:

我正在提交一个简单的表单,其中包含在数据库中命名的变量。

我正在尝试:

  1. 将提交的变量存储在数据库中(效果很好)
  2. 运行计算,然后将该值存储到数据库中

无论我尝试什么,我都会收到错误或'nil'(在@kcmil.inspect 上)作为@kcmil 的结果。我假设在我当前的代码中我没有将变量传递给模型,但即使它在控制器中也不起作用。

我在这里不知所措。我在表单存储中提交的变量就像预期的那样。我只想能够使用表单中提交的变量(这也是在提交时存储的数据库项目)并且在保存到数据库之前(或之后,是否重要?)运行计算并将结果存储在数据库中项目(以前没有从表单中调用或保存)。那有意义吗?非常感谢任何帮助或提示!

这是我当前的calculators_controller 创建和编辑操作:

  def create
   @calculator = Calculator.new(calc_params)
   if @calculator.save
      flash[:notice] = "Calculation created successfully."
      redirect_to(:action => 'index')
    else
      render('new')
    end
  end

  def update
    @calculator = Calculator.find(params[:id])
    if @calculator.update_attributes(calc_params)
     flash[:notice] = "Calculation updated successfully."
      redirect_to(:action => 'index', :id => @calculator.id)
    else
      render('edit')
    end
  end

private

 def calc_params
      params.require(:calculator).permit(:subsection, :amps, :volts, :distance, :vdrop, :phase, :kcmil, :section_id)
 end

这是我的模型

class Calculator < ActiveRecord::Base

before_create :kcmil_calc

def kcmil_calc
   if @phase == 1
          self.kcmil = ((13 * @distance.to_i * @amps.to_i ) / @vdrop.to_i).round(2)
       else
          self.kcmil = ((12.9 * @distance.to_i  * @amps.to_i ) / @vdrop.to_i).round(2)
      end
  end

end

【问题讨论】:

    标签: ruby forms variables model


    【解决方案1】:

    我有!我有!

    before_update :defaults
    
    def defaults
        if self.phase == 1
            self.kcmil = ((12.9 * distance * amps) / vdrop).round(2)
        else
            self.kcmil = ((13 * distance * amps) / vdrop).round(2)
        end
    end
    

    解决了!我不得不打电话给self.phase 而不是@phase 并将before_create 更改为before_update 才能让它工作。无需更改控制器。当 - 一个简单的@!我还删除了 to_i,因为它不需要,因为我的观点阻止我提交除整数以外的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多