我提交一个包含在数据库中命名的变量的简单表单。
我想:
无论我尝试什么,我都会收到错误或'nil'
(在@ kcmil.inspect上)作为@kcmil
的结果。我在我当前的代码中假设我没有将变量传递给模型,但即使它在控制器中也不起作用。
我在这里不知所措。我在表单中提交的变量按预期存储就好了。我只是希望能够使用表单中提交的变量(也是在提交时存储的数据库项)和保存到数据库之前(或之后,如果重要?)运行计算并将结果存储在数据库中item(以前未在表单中调用或保存)。那有意义吗?任何帮助或提示都非常受欢迎!!
以下是我目前的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
答案 0 :(得分: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因为它不需要,因为我的观点阻止我提交除整数以外的任何内容。