Problem with Stimulus and counter_culture gem (counter_cache)
Hy all, i have a problem with the counter_culture gem with my stimulus controller.
I have installed the gem and configured all.
I have 3 model :
Thats working fine for this relation: Category have a capsules_count column for counting how many capsules have a category
But i have a problem for counting the number of wishlist each Capsule have:
THE counter increase well in backend but in my frontend ( with stimulus ) i need to refresh the page for having the good value:
Here my models / controller and views !
CAPSULE
class Capsule < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
monetize :price_cents, allow_nil: true
geocoded_by :address
after_validation :geocode
ACCEPTED_CONTENT_TYPES = %w[image/png image/jpeg].freeze
has_many_attached :images
belongs_to :user
belongs_to :category
counter_culture :category, touch: true
has_many :wishlists, dependent: :destroy
has_many :wishlisted_users, through: :wishlists, source: :user, dependent: :destroy
end
WISHLIST
class Wishlist < ApplicationRecord
belongs_to :user
belongs_to :capsule
counter_culture :capsule
end
THE FRONT END
<div class="bg-white flex justify-center items-center rounded-md text-xs p-1" data-controller="wishlist-counter" data-capwishlists="<%= capsule.wishlists_count %>">
<span data-wishlist-counter-target="text"></span>
</div>
THE STIMULUS CONTROLLER
import {Controller} from "@hotwired/stimulus"
// Connects to data-controller="wishlist-counter"
export default class extends Controller {
static targets = ['counter', 'text'];
connect() {
this.textTarget.innerText = this.element.dataset.capwishlists;
}
}
When i click in the like button the value of my wishlists_count upgrade well but i need to refresh the page for stimulus in my front end to show the exact value and i dont know why ^ ^ ?
THE wishlists_count add + 1 value well in back end but the value is not INSTANTLY refreshed in my front end (stimulus) ...
Thanks you for anyone can help me.
It looks like the issue might be that counter_culture updates aren't triggering correctly with Stimulus-driven actions. Make sure you're calling the correct model methods that trigger the counter update, and check if the after_commit callbacks are firing. Also, try running the CounterCulture::Counter.reset_all to manually fix counts and see if it's a sync issue. Let me know more about your Stimulus setup—happy to help dig deeper!
Deltarune
When working with Rails and JS, it's best to use Visual Studio Code with specific extensions and settings to get the most out of the program. Students who are active in coding often benefit greatly from assignment help since it allows them to understand both coding and the configurations they need without sacrificing their class work, which can be a real burden. Drift Boss