如何创建2个具有不同ID的记录?

时间:2019-05-26 21:09:21

标签: ruby-on-rails

我有一个项目,人们需要在它们之间进行信贷交易。

我正在这样做

用户模型

class User < ApplicationRecord
  after_create :create_bank_account

  has_one :bank_account, inverse_of: :user, dependent: :destroy
  has_many :account_transactions, inverse_of: :user, through: :bank_account
end

银行模式

class BankAccount < ApplicationRecord
  belongs_to :user, inverse_of: :bank_account

  validates :balance, presence: true, numericality: true
  validates :user, presence: true

  has_many :account_transactions, inverse_of: :bank_account, dependent: :destroy
  accepts_nested_attributes_for :account_transactions

  before_validation :load_defaults

  def load_defaults
    if self.new_record?
    self.balance = 4.0
  end
end

帐户交易模型

class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :bank_account, inverse_of: :account_transactions

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    source_account = BankAccount.find(source)
    target_account = BankAccount.find(target)
    ActiveRecord::Base.transaction do
      source_account.balance -= amount
      target_account.balance += amount
      source_account.save!
      target_account.save!
    end
  end   
end

信用转移正常。

但是我需要使用每个用户的bank_id创建记录。

我将如何创建这2个帐户交易记录?

一条具有用户A的bank_id的记录,另一条具有用户B的bank_id的记录。

我不知道处理用户之间交易的最佳方法是否是这种方式

1 个答案:

答案 0 :(得分:1)

为什么AccountTransaction需要2条记录? 我强烈建议您在bank_account模型中保存2个AccountTransaction ID,请参阅:

# acount_transaction.rb
class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :target_bank_account, foreign_key: 'target_id', class_name: 'BankAccount'
  belongs_to :source_bank_account, foreign_key: 'source_id', class_name: 'BankAccount'

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    ActiveRecord::Base.transaction do
      self.source_bank_account.balance -= amount
      self.target_bank_account.balance += amount
      source_bank_account.save!
      target_bank_account.save!
    end
  end   
end

您只需要创建一个新迁移,即可将target_idsource_id添加到AcountTransaction

如果这样做,您将只保存1条记录source_accounttarget_account,这更有意义,您认为呢?

更新

您应该删除bank_id并为foreing_keys创建2个新的target_bank_idsource_bank_idAccountModel

BankAccount模型中,您可以添加以下几行:

# bank_account.rb
has_many incoming_transfers, foreign_key: 'target_bank_id', class_name: 'AccountTransaction' 
has_many made_transfers
, foreign_key: 'source_bank_id', class_name: 'AccountTransaction' 

之后,您可以检查每个BankAccount进行和接收了多少次转移!

您可以了解有关这种关联clicking here!

的更多信息