具有只读属性的模型?

时间:2018-02-05 13:06:37

标签: ruby-on-rails ruby-on-rails-5 rails-activerecord

我的模型有两个属性:A ast - 属性(jsonb),其中包含复杂的数据结构和compiled - 属性(string)可以随时从ast - 属性重新创建。

由于编译过程可能很长,我想在compiled - 属性发生更改时更新ast属性。对于这种缓存行为,我会使用before_save回调,只检查ast是否已更改,然后可能启动编译过程。

由于compiled - 属性严格依赖于ast - 属性,因此没有理由直接设置它。我想通过明确覆盖compiled=来做到这一点,但也许有更优雅的方法来做到这一点?在这种情况下,如何从回调中自己设置属性?

对我而言,这感觉就像我错过了Rails已经实现的一些功能。所以我没有像上面所描述的那样重新发明轮子,而是倾向于采用" Rails方式"。

1 个答案:

答案 0 :(得分:1)

我会远离回调并做类似的事情:

def ast=(value)
  super(value)
  self.send(:compiled=, from_ast(ast), force: true) # from_ast is meant to transform the data the way you need
end

def compiled=(value, force: false)
  super(value) if force
  # maybe raise if force is false?
end
相关问题