ruby-on-rails - 如何在保存一个模型之前更新另一个模型的数据

标签 ruby-on-rails ruby activerecord

我正在用 Rails 制作一个钱包应用程序。我不知道如何在交易中插入新记录之前更新用户模型中的余额字段。 当用户汇款时 user_id 是从隐藏字段中获取的,并且必须输入收件人的电子邮件和 user_id,user_email,amount 存储在事务表中。 如何从一条记录中扣除钱并添加到另一条记录中。我可以使用 sql update 来做到这一点吗?

这是用户模型

class User < ApplicationRecord

     devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

     has_many :transactions
end

这是该字段中包含的用户表余额。

create_table "users", force: :cascade do |t|
 t.string   "email"    
 t.string   "encrypted_password"   
 t.string   "reset_password_token"
 t.datetime "reset_password_sent_at"
 t.datetime "remember_created_at"
 t.integer  "sign_in_count"        
 t.datetime "current_sign_in_at"
 t.datetime "last_sign_in_at"
 t.string   "current_sign_in_ip"
 t.string   "last_sign_in_ip"
 t.datetime "created_at"                         
 t.datetime "updated_at"                      
 t.string   "Firstname"            
 t.string   "Lastname"               
 t.date     "Dob"
t.integer  "Balance"

结束

class Transaction < ApplicationRecord

     belongs_to :user
end

这是事务表。 user_id 是发件人,user_email 是收件人

create_table "transactions", force: :cascade do |t|
  t.integer  "user_id"
  t.string   "user_email"
  t.integer  "amount"
  t.datetime "created_at"
  t.datetime "updated_at"
end

最佳答案

你可以试试这段代码。用于从用户调用创建交易

current_user.transaction.new(transaction_params)

现在在模型 transaction.rb 文件中

class Transaction < ApplicationRecord
  belongs_to :user
  before_save :check_and_update_balance

  def check_and_update_balance
    ## since user or sender is already there no need of sender
    receiver = User.find_by(email: user_email)
    if user.has_sufficient_balance?(amount) and receiver.present?
       user.update_attributes(balance: balance - amount)
       receiver.update_attributes(balance: balance + amount)    
    end
  end
end

希望这有帮助!!

关于ruby-on-rails - 如何在保存一个模型之前更新另一个模型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42960479/

相关文章:

ruby-on-rails - 在 CSS 中传递 ruby​​ 标签

ruby-on-rails - 与非类/模块错误相比

ruby-on-rails - 为 Rails 上的列 ruby​​ 指定默认值

mysql - 在 JRuby 上使用 ActiveRecord 对 MariaDB 的首次查询需要 5 分钟以上才能执行

ruby-on-rails - ROR 按时间上彼此的接近程度进行分组

ruby-on-rails - Mongoid 创建空集合

mysql - 轨道 3 : Measure database performance (MongoDB and MySQL)

ruby-on-rails - 如何在rails中获取simple_form的动态id

html - 网站无法在移动设备上正确调整大小

ruby-on-rails - 如何在 Rails 中干燥模型?