所以我正在阅读 touch
here 的文档看起来 touch: true
只能放在belongs_to 关系上。然而,在我的世界中,我希望触摸的对象是 has_one
关联。
我的数据模型:
class Tool
has_one :product, as: :producible, inverse_of: :producible
end
class Product
belongs_to :producible, polymorphic: true
end
所以我想要的是每次更新工具时,产品
也会更新。如何做到这一点?我似乎无法使用 touch: true
。
另外,as:
和 inverse_of:
对我有什么作用?
最佳答案
这里有一篇很好的文章解释了 inverse_of
的使用:https://www.viget.com/articles/exploring-the-inverse-of-option-on-rails-model-associations
如果您想要触摸
关联的模型,您可以将其添加到您的工具类中:
after_save :touch_product
private
def touch_product
product&.update_column(:updated_at, Time.now)
end
这实际上与触摸
相同。它将更新产品记录中的时间戳,而无需实例化对象或运行任何回调。如果您有兴趣进一步阅读,可以在此处找到 touch
方法的源代码: https://apidock.com/rails/ActiveRecord/Persistence/touch
关于ruby-on-rails - Rails,如何触摸 has_one 关系中的更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46672807/