如何使用当前行的另一个属性值从最后一行添加属性值

时间:2015-04-23 01:30:47

标签: ruby-on-rails ruby

基本上我有一个具有以下属性的表:id,created_at,updated_at,user_id,email,debit,credit和acctbal。我使用Rails,并且我在具有帐户历史记录的页面上有一个添加资金按钮。如果我存入50.00,它将在该表中正确添加一个新行,并在存款属性中放入50,保持信用无效。但是acctbal属性也是null,我无法弄清楚如何将当前信用值添加到该表中最后一行的acctbal值。我正在使用RoR。我将使用相同的技术作为借方值。我的创建方法是以下没有acctbal的计算因为我被卡住了。

def create
#@account = Account.new(account_params)
# @account.save
# respond_with(@account)
@account = Account.new(account_params)
@account.email = current_user.email
@account.user_id = current_user.id
respond_to do |format|
  if @account.save
    format.html { redirect_to accounts_url, notice: 'Thank you and enjoy.' }
    format.json { render :show, status: :created, location: @account }
  else
    format.html { render :new }
  format.json { render json: @account.errors, status::unprocessable_entity }
  end
 end
end
任何人都可以帮助我,手指在尝试一堆我在网上找到的东西时流血但无济于事。

1 个答案:

答案 0 :(得分:0)

我认为你所得到的是:

def credit
  @previous_balance = Account.where('user_id = ?', current_user.id).order(:created_at).last.acctbal
  @account = Account.new(account_params)
  @account.email = current_user.email
  @account.user_id = current_user.id
  @account.acctbal = account_params[:deposit] + @previous_balance 
  respond_to do |format|
    if @account.save
      format.html { redirect_to accounts_url, notice: 'Thank you and enjoy.' }
      format.json { render :show, status: :created, location: @account }
    else
      format.html { render :new }
      format.json { render json: @account.errors, status::unprocessable_entity }
    end
  end
end

正如我在上面的评论中所说的那样,你只是将他们最后一次创建的行的最后余额与他们的ID相加并将其添加到存款中。有两点需要注意:   1)如果这是你的方式,你不应该在这个表中update行,或者如果你这样做,你应该使用updated_at属性。   2)您应该在created_at属性上放置一个索引,以防止在表变大时对数据库进行拖动。

相关问题