ruby-on-rails - Rails,如何触摸 has_one 关系中的更新?

标签 ruby-on-rails activerecord

所以我正在阅读 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/

相关文章:

ruby-on-rails - 让 find_by in rails 返回多个结果

ruby-on-rails - Heroku Rails - 关闭 Active Record Postgres 连接

ruby-on-rails - 在生成模型时指定限制的语法

html - Rails 3 不将 HTML 呈现为标记

ruby-on-rails - 优化 Rails 急切加载查询以查找全部

mysql - has_and_belongs_to_many 连接表中不允许使用主键

ruby-on-rails - Cucumber 和 Rails - 打印场景

ruby-on-rails - 如何获取数组中的下一个和上一个元素,Ruby

ruby-on-rails - Rails 3 - CanCan 错误? NameError(未初始化的常量 Ability::Invitation):

ruby-on-rails - Rails & Devise - 跨子域自动登录