更新 Rails 中多态关联的时间戳
我有一个可以属于其他两个模型的照片模型,这是通过多态关联捕获的:
has_many :photos, :as => photo_container
我想在创建新照片时更新 photo_container 模型的时间戳。我在照片模型中使用 after_create 回调执行此操作:
self.photo_container.update_attribute(:updated_at, Time.now)
由于我的两个 photo_container 模型都有 update_attribute 字段,因此它应该工作正常,但是,我在回调中的相应行中收到以下异常:
NameError (uninitialized constant Photo::PhotoContainer)
当然,如果我检查 photo_container 的类型,加载模型并更改时间戳,但它不是干净/通用的。有什么想法吗?
I have a Photo model that can belong to two other models and this is captured through a polymorphic association:
has_many :photos, :as => photo_container
I would like to update the timestamp of the photo_container models when a new photo is created. I am doing this with an after_create callback in the Photo model:
self.photo_container.update_attribute(:updated_at, Time.now)
Since both my photo_container models have an update_attribute field it should be working fine, however, I am getting the following exception for the corresponding line in the callback:
NameError (uninitialized constant Photo::PhotoContainer)
Of course it works fine if I check the type of photo_container, load the model and change the timestamp but it is not clean/generic. Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 belongs_to 关联中的触摸选项。它应该工作正常。像这样的东西:
Use the touch option in the belongs_to association. It should work fine. Something like: