I'm building a blog app on rails, so i created a method to update the number of posts when a new post is added by a certain user (user and post are my models).
class Post < ApplicationRecord
belongs_to :author, class_name: 'User', foreign_key: 'user_id'
has_many :comments
has_many :likes
after_save :update_user_counter
validates :title, presence: true, length: { maximum: 250 }
validates :comments_counter, :likes_counter, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
after_initialize do |post|
post.comments_counter = 0
post.likes_counter = 0
end
def update_user_counter
author.increment!(:posts_counter)
end
def recent_5_comments
comments.order(created_at: :desc).limit(5)
end
private :update_user_counter
end
I test the method using rails console as follows
- I start to review the previously created user posts_counter values you can see they start in 0
I create a variable to store the first user using User.find(1)
I create a new post to that user
4.When runing the last step the posts_counter gets updated and shows 1 when variable is called
5.But when running User.all the value is again 0
Is there a way to fix this? I need to be able to see the changes when i run User.all I have tried changing my method but it seems it does not change anything, I'm sorry for the extension of the question I'm starting learning rails and this is frustrating.



