在我的应用程序中,Conversation有很多消息.如何updated_at在创建/保存该对话中的新消息时更新对话的属性?
我知道:touch => true,这样做,但它也会在消息被销毁时更新对话,这不是我想要的.
谢谢.
楷模
class Conversation < ActiveRecord::Base
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
end
Run Code Online (Sandbox Code Playgroud)
chu*_*g2k 58
您也可以在关系上定义它.
class Message < ActiveRecord::Base
belongs_to :conversation, touch: true
end
Run Code Online (Sandbox Code Playgroud)
(来源与William G的答案相同:http://apidock.com/rails/ActiveRecord/Persistence/touch)
Ana*_*oly 40
在Message类中使用回调
after_save do
conversation.update_attribute(:updated_at, Time.now)
end
Run Code Online (Sandbox Code Playgroud)
小智 9
我更喜欢Rails 3的这个解决方案:
class Message < ActiveRecord::Base
belongs_to :conversation
after_save :update_conversation
def update_conversation
self.conversation.touch
end
end
Run Code Online (Sandbox Code Playgroud)
资料来源:http://apidock.com/rails/ActiveRecord/Persistence/touch
| 归档时间: |
|
| 查看次数: |
12319 次 |
| 最近记录: |