0

I want to be able to manage has_many caching myself. The issue being I want to be able to archive (like soft delete, but with discardable gem) some records:

has_many :tags

def tag_list=(tag_names)

  # so I do a diff
  names_to_create = ...  
  tags_to_discard = ...
  tags_to_keep = ...

  to_delete.each(&:discard)
  new_tags = names_to_create.each { |name| tag.create!(name: name) }

  # if I just go with regular
  self.tags = new_tags + tags_to_keep
  # tags_to_discard will be deleted

The thing is that I don't want to just tags.reload. It's costly I know exactly what tags should be here or not.

How I can just "force" the rails cache?

1 Answer 1

0

You should tread carefully with that, but I find that

has_many :tags

def tag_list=(tag_names)

  # Do a diff
  names_to_create = ...  
  tags_to_discard = ...
  tags_to_keep = ...

  to_delete.each(&:discard)
  new_tags = names_to_create.each { |name| tag.create!(name: name) }

  tags.proxy_association.target = tags_to_keep + new tags
end

To do exactly that

Though it's probably private API and not meant to be used like that.

2
  • Yeah, I would not mess with Rails internals like that.
    – Eyeslandic
    Commented Oct 3, 2022 at 21:53
  • But worked perfectly in this case withouht any side effects. This is a winning tradeoff because having to reload and hit the DB each time IS costly Commented Oct 4, 2022 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.