如何在表单提交后执行ActiveRecord查询?

时间:2017-07-17 19:39:32

标签: ruby-on-rails activerecord

这会有用吗?我想做像硬币转移这样的事情

@logs = Logs.new(log_params)
@logs.save
@tt = Users.where(email: params[:email]).update(money: Users.find(current_user.id)['money'] - params[:money])
@tt.save
@wr = Users.find(current_user.id).update(money: Users.where(email: params[:email])['money'] + params[:money])
@wr.save

1 个答案:

答案 0 :(得分:1)

我不知道您是否打算在视图中显示这些值,但您可以这样做:

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]

然后你的交易会有点干燥

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

但恕我直言,我会做这样的事情:

模型/ User.rb

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

在您的控制器中

amount = params[:money].to_i
User.transaction do
  @logs = Logs.new(log_params)
  @tt = sender.sends_money(amount)
  @wr = recipient.receives_money(amount)
end

这使您可以更轻松地阅读和遵循代码。

希望这有帮助!