如何在Rails的ActiveRecord列上附加字符串

rock_n_rolla

我有一个股份的概念,它代表特定股东拥有的特定股票。我现在要添加的功能是支持随时间推移跟踪此股票的“历史记录”,因为它可以转移给其他股东等。

在我的数据库中,每个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_idsinteger带有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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Vim中用旧字符串+附加字符串替换字符串

如何在Swift中将字符附加到字符串?

如何在elasticsearch中将字符附加到字符串?

如何在Java中删除附加的字符串

如何在javascript字符串之间附加内容?

如何在Python中将字符串附加到路径?

如何在JavaScript中限制附加字符串?

如何在C ++中从循环附加字符串?

如何在PHP中用逗号附加字符串

如何在变量末尾附加字符串?

如何在bash中将日期附加到字符串

批处理:如何在FOR循环中附加字符串

如何在if条件中附加字符串值

如何在ocaml中附加字符串?

如何在Clojure中将字符串附加到向量

如何在JSP测试属性中附加字符串

如何在Xcode中将变量附加到字符串

如何在C ++中将long附加到字符串?

如何在php变量上附加字符串

如何在Rails控制台中查找和删除字符串的一部分-ActiveRecord

如何在字符串数组的特定索引处附加字符串

如何在循环中将相同的字符串变量附加到字符串

如何在Swift中使用属性字符串附加属性文本字符串

如何在模式之前附加字符串,同时保持字符串原样?

如何在字符串末尾附加一个字符串?

如何在R中的列上提取子字符串,删除所有%字符

如何在前 2 列上添加字符串并在第 3 列上为 pyqt tablewidget 中的每一行字符串添加按钮?

如何在熊猫数据框列上打印给定字符串的出现?

如何在特定列上打印包含多行的整个字符串?