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