I am using Ruby on Rails 3.2.2 and I would like to set a counter cache value to a "custom" one. That is, at this time (in my migration file) I am trying to use the following code:
def up
add_column :articles, :comments_count, :integer, :default => 0
Article.reset_column_information
Article.find_each do |article|
# Note: The following code doesn't work (when I migrate the database it
# raises the error "comments_count is marked as readonly").
Article.update_column(:comments_count, article.custom_comments.count)
end
end
In other words, I would like to set the :comments_count
value (a counter cache database table column) to a custom value (in my case that value is article.custom_comments.count
- note: the custom_comments
is not an ActiveRecord Association but a method stated in the Article
model class; it returns an integer value as well) that is not related to a has_many
associations.
Maybe, I could / should use something like
Article.reset_column_information
Article.find_each do |article|
Article.reset_counters(article.id, ...)
end
but it seems that the reset_counters
method cannot work without has_many
associations.
How can I set the :comments_count
counter cache value to a given value that is related to a "custom association"?