Problem with counter_cache implementation

前端 未结 2 1489
面向向阳花
面向向阳花 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:43

    OK, the documentation states:

    Counter cache columns are added to the containing model’s list of read-only attributes through attr_readonly.

    I think this is what happens: you declare the counter in the model's definition, thus rendering the "posts_count" attribute read-only. Then, in the migration, you attempt to update it directly, resulting in the error you mention.

    The quick-and-dirty solution is to remove the counter_cache declaration from the model, run the migration (in order to add the required column to the database AND populate it with the current post counts), and then re-add the counter_cache declaration to the model. Should work but is nasty and requires manual intervention during the migration - not a good idea.

    I found this blog post which suggests altering the model's list of read-only attributes during the migration, it's a bit oudated but you might want to give it a try.

提交回复
热议问题