Reputation: 17737
I have a the following models:
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
When I add attachments to a note, I do it via the part
def update
@part = current_user.parts.find params[:id]
@part.note.update note_params
…
end
What I find strange is the following:
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
Why does the first call return false? Since I need this in my view, I'm left with calling @part.note.reload, but I can't understand what is going on.
Thanks
Upvotes: 1
Views: 756
Reputation: 10328
Associations are cached for performance reasons. Use association(true)
to bypass the cache and force Rails to refetch the current state after you have done something to change it:
@part.note(true).attachments.any?
See Association Basic: Controlling Caching.
Upvotes: 4