1

我有以下型号:

class Part
  belongs_to :note, inverse_of: :part, dependent: :destroy

class Note
  has_many :attachments, as: :attachable, dependent: :destroy
  has_one :part, inverse_of: :note
end

class Attachment
  belongs_to :attachable, polymorphic: true, touch: true
end

当我在笔记中添加附件时,我是通过部件来完成的

def update
  @part = current_user.parts.find params[:id]
  @part.note.update note_params
  …
end

我觉得奇怪的是:

def update
  @part = current_user.parts.find params[:id]
  @part.note.update note_params
  @part.note.attachments.any? # => false
  @part.note.attachments.any? # => true
end

为什么第一次调用返回 false?因为在我看来我需要这个,所以我只能调用@part.note.reload,但我不明白发生了什么。

谢谢

4

1 回答 1

4

出于性能原因缓存关联。用于association(true)绕过缓存并强制 Rails 在您完成更改后重新获取当前状态:

@part.note(true).attachments.any?

请参阅关联基本:控制缓存

于 2015-02-19T09:44:18.130 回答