【问题标题】:Rails: Update parent object when saving childRails:保存子对象时更新父对象
【发布时间】:2011-07-18 16:39:45
【问题描述】:

在我的应用中,对话有很多消息。创建/保存对话中的新消息时,如何更新对话的updated_at 属性?

我知道:touch => true,它会这样做,但它也会在消息被销毁时更新对话,这不是我想要的。

谢谢。

型号

class Conversation < ActiveRecord::Base
  has_many :messages 
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你也可以在关系上定义它。

    class Message < ActiveRecord::Base
      belongs_to :conversation, touch: true
    end
    

    (来源与 William G 的答案相同:http://apidock.com/rails/ActiveRecord/Persistence/touch

    【讨论】:

    • 这不会运行回调!!大多数情况下,您想要执行此操作是在您想要运行父回调时。
    • 来自原问题:How to I update the updated_at attribute of a Conversation when a new Message in that Conversation is created/saved? .touch 方法主要用于更新时间戳。 (来自文档:Saves the record with the updated_at/on attributes set to the current time.touch 最常见的用法可能是缓存到期。如果你想要回调,有一个after_touch 回调。
    • 另一种用途是站点地图时间戳,在这种情况下不需要回调。
    • @chug2k id touch: true 用于销毁子对象。意味着当关联消息被删除时,它会更新对话对象吗??
    【解决方案2】:

    在 Message 类中使用回调

    after_save do
      conversation.update_attribute(:updated_at, Time.now)
    end
    

    【讨论】:

    • 你能告诉我为什么即使不提self.conversation...也能工作。何时何地不使用self
    • @HungryCoder 在您进行属性分配时使用 self 以防止任何歧义(例如,您具有相同名称的局部变量)。但在那种情况下,conversation 不是局部变量,而是显式声明的关联(例如,方法的名称)
    【解决方案3】:

    我更喜欢 Rails 3 的这个解决方案:

    class Message < ActiveRecord::Base
      belongs_to :conversation
    
      after_save :update_conversation
    
      def update_conversation
        self.conversation.touch
      end
    end
    

    来源:http://apidock.com/rails/ActiveRecord/Persistence/touch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 2012-08-25
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多