我很难弄清楚如何做到这一点。我整天都在做这件事。
我有一个 Account 类和一个 Transaction 类。帐户是使用余额创建的,我希望交易金额根据其类型从余额中增加或减少。
我希望能够在每次创建交易时更新账户余额。这是个人理财应用程序。截至目前,当我创建新交易时,账户余额没有任何变化。
account_controller.rb
class AccountsController < ApplicationController
def index
@accounts = Account.all
end
def show
@account = Account.find(params[:id])
end
def new
@account = Account.new
end
def edit
@account = Account.find(params[:id])
end
def create
@account = Account.new(params[:account])
respond_to do |format|
if @account.save
format.html { redirect_to @account, notice: 'Account was successfully created.' }
format.json { render json: @account, status: :created, location: @account }
else
format.html { render action: "new" }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
def update
@account = Account.find(params[:id])
respond_to do |format|
if @account.update_attributes(params[:account])
format.html { redirect_to @account, notice: 'Account was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
# DELETE /accounts/1
# DELETE /accounts/1.json
def destroy
@account = Account.find(params[:id])
@account.destroy
respond_to do |format|
format.html { redirect_to accounts_url }
format.json { head :no_content }
end
end
def update_balance
@a = Account.find(params[:id])
@a.transactions.each do |t|
@update_balance = t.t_type + @a.balance
@a.update_attributes(:balance => @update_balance)
end
end
end
交易控制器.rb
class TransactionsController < ApplicationController
def create
@account = Account.find(params[:account_id])
@transaction = @account.transactions.create(params[:transaction])
redirect_to account_path(@account)
end
end
事务.rb
class Transaction < ActiveRecord::Base
belongs_to :account
attr_accessible :amount, :category, :t_type
end
帐号.rb
class Account < ActiveRecord::Base
attr_accessible :balance, :name
has_many :transactions
end
如果有人知道我做错了什么,或者可以为我指出一个好的彻底解释的方向,那就太好了。在这一点上我很迷茫。