2014-07-10 42 views
0

我想用兩個提交的表單變量做一個簡單的計算,然後將所有三個變量存儲在數據庫中。每個變量都是我數據庫中的一列。簡單的計算和存儲到紅寶石數據庫

E.G.

somedbfield = (item_1 * item_2) + 2 

我在形式將如何提交,somedbfielditem_1item_2保存在測試數據庫?所有三個項目都在validates_numericality_of驗證在模型中,他們應該都是整數。這只是我的基本代碼,找出從提交表單的test.id,但我不知道如何使用表單值來創建一個計算,然後所有三個值向數據庫提交:

class Test_Controller < ApplicationController 

     def update 
     @test = Test.find(params[:id]) 
      respond_to do |format| 
      if @test.update(test_params) 
      format.html { redirect_to('index', :notice => 'User was successfully updated.') } 
      format.json { respond_with_bip(@test) } 
      else 
      format.html { render :action => "edit" } 
      format.json { respond_with_bip(@test) } 
      end 
     end 

private 

def test_params 
     params.require(:test).permit(:item_1, :item_2, :somedbfield) 
end 

end 

這是一個更簡單的問題的版本,我以前問,但無法得到任何答案,所以我只是想簡化,並從那裏工作。

謝謝!

+0

你的問題是什麼?發佈您的當前代碼,並告訴我們有什麼問題,以便我們提供幫助。 – Martin

+0

@Martin更新... – KevinW

回答

0

我看到它的方式,您的update方法只是檢索模型的一個實例,並保存它沒有做任何事情。

要更新數據庫,你就需要在參數的情況下通過,然後將其保存:

item_1 = params[:item_1] 
    item_2 = params[:item_2] 
    somedbfield = (item_1 * item_2) + 2 
    @test.update(:item_1 => item_1, :item_2 => item_2, :somedbfield => somedbfield) 
0

你應該使用params[:symbol]語法這一點。您可以使用:

@test.item_1=params[:item_1] 
@test.item_2=params[:item_2] 
@test.somedbfield=params[:item_1]*params[:item_2]+2 
@test.save 

讓我知道這是否有幫助。

+0

你可以再看一下,因爲我已經有一個if @ test.update(test_params)它不起作用? – KevinW