A
Adam42Smith
Hi. I have a problem with counters in Rails. The situation looks like
this:
-3 simple models
class Forum < ActiveRecord::Base
has_many osts
end
class Topic < ActiveRecord::Base
has_many osts
end
class Post < ActiveRecord::Base
belongs_to :topic, :counter_cache => true
belongs_to :forum, :counter_cache => true
end
- In migrations i have declared
t.column osts_count, :integer, :default => 0
for Forum and Topic
- Now a simple action
def some_action
@post = Post.new(params[:id])
@forum.posts << @post # The @forums.posts_count is up by 1
@topic.posts << @post # The @topic.posts_count is _not_ up by 1
end
Both, the forum_id and topic_id are set correctly in @post, it saves
into the database and everything else is dandy. But why oh why doesn't
the @topic.posts_count increment ? (oh, obviously if I change the
order
of the two crucial lines the effect will be the same - the instance in
the second line won't get the posts_count incremented)
Could anyone come up with a solution ? (apart from making the counters
'by hand')
this:
-3 simple models
class Forum < ActiveRecord::Base
has_many osts
end
class Topic < ActiveRecord::Base
has_many osts
end
class Post < ActiveRecord::Base
belongs_to :topic, :counter_cache => true
belongs_to :forum, :counter_cache => true
end
- In migrations i have declared
t.column osts_count, :integer, :default => 0
for Forum and Topic
- Now a simple action
def some_action
@post = Post.new(params[:id])
@forum.posts << @post # The @forums.posts_count is up by 1
@topic.posts << @post # The @topic.posts_count is _not_ up by 1
end
Both, the forum_id and topic_id are set correctly in @post, it saves
into the database and everything else is dandy. But why oh why doesn't
the @topic.posts_count increment ? (oh, obviously if I change the
order
of the two crucial lines the effect will be the same - the instance in
the second line won't get the posts_count incremented)
Could anyone come up with a solution ? (apart from making the counters
'by hand')