Rails 4.2:更新关系,通过关系……

Rails 4.2: updating relationships, via a relationship…

我有以下型号:

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

为什么第一个调用 return 是错误的?因为在我看来我需要这个,所以我只能调用@part.note.reload,但我不明白发生了什么。

谢谢

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

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

参见Association Basic: Controlling Caching