ruby-on-rails - 如何附加到 Rails 中 ActiveRecord 列上的字符串

标签 ruby-on-rails ruby activerecord

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

在我的数据库中,对于每个 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

然后当一个Share被转移时,我有下面的方法。

@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 被转移时,您可以执行以下操作:

@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各方何时验证传输等。您甚至可以锁定 ShareTransfer 表为“仅插入”,防止任何用户(或代码)更新其中的数据并确保日志的完整性。

关于ruby-on-rails - 如何附加到 Rails 中 ActiveRecord 列上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53833629/

相关文章:

ruby-on-rails-3 - RSpec 中的动态定义方法抛出错误

ruby-on-rails - 无法修改关联 'SomeModels',因为它经过多个其他关联

mysql - 运行 rails g devise :install generates seg fault in os x 10. 8

ruby - Ruby 中的 include 和 require 有什么区别?

ruby - 如何从文本 block 中删除重复项

mysql - 如何在rails 3事件记录查询中转换以下查询?

ruby-on-rails - Rails erb 检查是否存在并执行每个

ruby-on-rails - Rails 3 - has_many 通过嵌套形式

ruby - 类实例的 Rspec stub 期望

ruby-on-rails-3 - 如何清除模型的 :has_many associations without writing to the database in ActiveRecord?