开发者

Update the timestamp on a polymorphic association in Rails

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:

Na开发者_如何学CmeError (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?


Use the touch option in the belongs_to association. It should work fine. Something like:

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true, :touch=>true
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜