counter-cache

Problem with counter_cache implementation

∥☆過路亽.° 提交于 2019-12-02 14:17:30
I'm getting 'rake aborted! ... posts_count is marked readonly' errors. I have two models: user and post. users has_many posts. posts belongs_to :user, :counter_cache => true I have a migration which adds the posts_count column to the users table and then calculates and records the current number of posts per user. self.up add_column :users, :posts_count, :integer, :default => 0 User.reset_column_information User.all.each do |u| u.update_attribute( :posts_count, u.posts.count) end end when I run the migration I get the error. This is pretty clear-cut, of course and if I remove the :counter

Rails 4: counter_cache in has_many :through association with dependent: :destroy

梦想的初衷 提交于 2019-12-01 21:08:05
Although similar questions have already been asked: counter_cache with has_many :through dependent => destroy on a "has_many through" association has_many :through with counter_cache none of them actually addresses my issue. I have three models, with a has_many :through association : class User < ActiveRecord::Base has_many :administrations has_many :calendars, through: :administrations end class Calendar < ActiveRecord::Base has_many :administrations has_many :users, through: :administrations end class Administration < ActiveRecord::Base belongs_to :user belongs_to :calendar end The join