ActiveRecord派生的属性持久性取决于id值

Cha*_*tni 1 activerecord ruby-on-rails

如何持久化依赖于rails中id值的派生属性?下面的片段似乎有用 - 有更好的轨道方式吗?

class Model < ActiveRecord::Base
  ....
  def save
    super
    #derived_attr column exists in DB
    self.derived_attr = compute_attr(self.id)
    super
  end
end
Run Code Online (Sandbox Code Playgroud)

EmF*_*mFi 5

提供回调,因此您永远不必覆盖保存.以下代码中的before_save调用在功能上等同于问题中的所有代码.

我已经将set_virtual_attr设为public,以便可以根据需要进行计算.

class Model < ActiveRecord::Base
  ...
  # this one line is functionally equivalent to the code in the OP.
  before_save :set_virtual_attr
  attr_reader :virtual_attr

  def set_virtual_attr
    self.virtual_attr = compute_attr(self.id)
  end
  private
  def compute_attr
    ...
  end  
end
Run Code Online (Sandbox Code Playgroud)