0

I have two ActiveRecord models List and ListItem as shown below.

class List < ApplicationRecord
  has_many :items, -> { order(position: :asc) }, 
            class_name: "ListItem", 
            dependent: :destroy, 
            counter_cache: :items_count

  has_one :first_item, -> { order :id }, 
           class_name: "ListItem"

end
class ListItem < ApplicationRecord
   belongs_to :list, 
               counter_cache: :items_count, 
               touch: true
end

When I create a new ListItem, the counter cache field items_count is updating correctly. But when I destroy one, the count is not decrementing. Is there something wrong with this association or the counter cache implementation?

I checked a few already answered questions, like this one: counter_cache not decrementing for has_many associations in ActiveReord . Both the solutions suggested in the answers didn't work for me.

This is how I delete a list item in the controller:

def destroy
  list = current_user.lists.find_by(identifier: params[:list_identifier])
  if list
    list.items.find(params[:id]).destroy!
    head :no_content
  else
    render status: :not_found, json: { errors: "Invalid list" }
  end
end
Yedhu Krishnan
  • 1,225
  • 15
  • 31
  • 1
    Are you destroying or deleting list items? Can you see the SQL transaction logs after destroying a list item? – Sebastián Palma Dec 21 '20 at 09:52
  • @SebastianPalma I am using the `destroy` method. I can see the SQL logs. If I try `List.last.items.count`, I get the correct count. But `List.last.items_count` gives me the count before destroying. – Yedhu Krishnan Dec 21 '20 at 10:09
  • What happens if you call `List.last.reload` before `List.last.items_count`? – dbugger Dec 21 '20 at 14:39
  • @dbugger I tried that. The count doesn't change even after `reload`. – Yedhu Krishnan Dec 21 '20 at 15:24
  • What happens if you remove `counter_cache: :items_count` from the has_many? – dbugger Dec 21 '20 at 15:33
  • The same. I started from there actually. I added that as per [the answer here](https://stackoverflow.com/a/54071817/2139625). – Yedhu Krishnan Dec 21 '20 at 15:39
  • Can you show the code where the `ListItem` is removed? Also your specific rails version would be helpful in this case – engineersmnky Dec 21 '20 at 16:16
  • @engineersmnky Sure. I've updated the question with the controller method I use. I also tried `List.last.items.last.destroy!` from the rails console. That also didn't decrement the counter for `List.last`. – Yedhu Krishnan Dec 22 '20 at 05:00

0 Answers0