を転送コインのような何かをしたい:
sender = Users.where(email: params[:email]).first
# This returns the user
recipient = Users.find(current_user.id)
# or just current_user if it inherit from the User class
money_to_substract = recipient.money - params[:money]
money_to_sum = recipient.money + params[:money]
次に、あなたのtranssaction
:
User.transaction do
@logs = Logs.new(log_params)
@tt = sender.update(money: money_to_substract)
# update saves to the database so no need to call save
# @tt.save
@wr = recipient.update(money: money_to_sum)
# update saves to the database so no need to call save
# @wr.save
end
しかし、私見ビットdryierだろう、私はこのような何かをするだろう
モデル/ User.rb読んで、あなたのコードフォロースルーする事が容易になり、あなたのコントローラ
amount = params[:money].to_i
User.transaction do
@logs = Logs.new(log_params)
@tt = sender.sends_money(amount)
@wr = recipient.receives_money(amount)
end
で
class User < ActiveRecord::Base
...
def sends_money(amount)
money_to_substract = self.money - amount
update(money: money_to_substract)
end
def receives_money(amount)
money_to_sum = self.money + amount
update(money: money_to_sum)
end
...
end
。
希望すると便利です。
お金のオブジェクトには、トランザクションでラッピングし、ソリッド検証サービスを使用することをお勧めします。単純に 'params [:money]'を渡してはいけません。 $$$ ^^をつまらないでください。 –
さらに、MoneyTransferモデルを作成してトランザクションを追跡することもできます。残高は、すべての取引が適用された後のスナップショットです。そうでなければ物事は乱雑になるかもしれません。 –
ありがとう、それは本当に有用だった – Fluffy