Problem with counter_cache implementation

前端 未结 2 1485
面向向阳花
面向向阳花 2020-12-23 01:55

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 :         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-23 02:35

    You should be using User.reset_counters to do this. Additionally, I would recommend using find_each instead of each because it will iterate the collection in batches instead of all at once.

    self.up
      add_column :users, :posts_count, :integer, :default => 0
    
      User.reset_column_information
      User.find_each do |u|
        User.reset_counters u.id, :posts
      end
    end
    

提交回复
热议问题