我有一个股份的概念,它代表特定股东拥有的特定股票。我现在要添加的功能是支持随时间推移跟踪此股票的“历史记录”,因为它可以转移给其他股东等。
在我的数据库中,每个Share
记录当前都有一列t.string "transaction_ids"
。我可能应该将假设的列类型更改为更易于使用的列。在这里开放建议。
两种相关方法是创建新股份然后转移股份所有权。
这是最初创建共享的方式。
@number_of_share_numbers_to_create.times do |i|
Share.create(
owner_id: params[:buying_shareholder_id],
captable_id: @transaction.captable.id,
company_id: @transaction.company.id,
share_number: @latest_share += 1,
transaction_ids: @transaction.id #Save transaction id to DB
)
end
然后,当aShare
被转移时,我有以下方法。
@share_numbers_on_cap.each do |share|
share.update_attribute(:owner_id, @buying_shareholder.id)
# TODO Capture share history by pushing @transaction.id into the transaction_ids column.
# Perhaps I could do something like share.transaction_ids >> @transaction.id or something?
end
我知道当前的解决方案不是最佳解决方案,我希望获得有关如何以更可扩展的方式解决此问题的指导。也许我应该使用其他列类型并构建一个数组?很乐意向正确的方向推进。
谢谢!
我建议创建另一个模型来“记录”特定Share
对象发生的事务。
例如:
class ShareTransfer < ApplicationRecord
belongs_to :share
belongs_to :transaction
# don't forget to enforce the presence of
# both foreign keys share_id and transaction_id
# bonus: "freezing" the object after creation so you can never
# update the logged object (= data integrity)
before_save(on: :update) do
errors.add(:base, :immutable, "Cannot update a frozen object")
end
end
并将您的当前内容更改Share#transaction_ids
为integer
带有transactions
表外键的简单列(可能也将其重命名)以得到如下结果:
class Share < ApplicationRecord
belongs_to :transaction # implies you have renamed the column transaction_ids to transaction_id (and changed the column type)
has_many :share_transfers
end
Share
转移a时,您可以执行以下操作:
@share_numbers_on_cap.each do |share|
# [your previous logic to change ownership]
share.share_transfers.create!(transaction_id: share.transaction_id)
# ^ to create history of the ownership change
end
此架构允许您向ShareTransfer
模型添加额外的字段,例如,发生转移的确切时间(例如occurred_at
:),验证转移时双方的IP等。您甚至可以lock
将该ShareTransfer
表设为“仅插入” ”,以防止任何用户(或代码)更新其中的数据,并确保日志的完整性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句