Start Rails counter cache not updating

Rails counter cache not updating

At face value, that sure sounds like a bad deal, right?

Plus, there’s no objects in Elixir which means automatic incrementing of a model field in the background just isn’t possible. To ensure the comment_count field on the respective Post is incremented only when the Comment is persisted to the database, we need to use Ecto. Web, :model schema "comments" do field :title, :string field :body, :string field :comment_count, :integer belongs_to :post, Counter Caching.

So, thinking about the problem functionally, whenever a Comment is created we will want to increment the value of comment_count on the Post model (note the singular “comment_count”, this is Phoenix convention as opposed to plurals in Rails with the exception of database table names). Well, as with any other Phoenix model, we have a changeset that casts all of the required fields from the supplied params. Changeset.prepare_changes/2From the documentationdefmodule Counter Caching. Post timestamps end def changeset(struct, params \\ %) do struct |prepare_changes takes a changeset and an anonymous function. Now the Post which belongs to our new Comment will only have its comment_count field incremented when the Comment is persisted to the database.

Are there things that could be improved on, however? Elixir and Phoenix have the luxury of being new and doing things right from day one.

After reading this guide, you will know: Migrations are a convenient way to alter your database schema over time in a consistent and easy way.

Therefore, there’s no such counter_cache option to just switch on in your models.

What you’ll need to do is leverage the power of changeset’s and increment association counts yourself.

From what I can tell the uploading of reports and facts from the 40K nodes, through the puppet masters, is causing the deadlocks.