Rails: Counter problem

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 :posts
end
class Topic < ActiveRecord::Base
has_many :posts
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 :posts_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')
 
L

Lloyd Linklater

At the risk of sounding simplistic, wouldn't it be

class Forum < ActiveRecord::Base
has_many :topics
end
class Topic < ActiveRecord::Base
has_many :posts
belongs_to :forum, :counter_cache => true
end
class Post < ActiveRecord::Base
belongs_to :topic, :counter_cache => true
end
 
A

Adam42Smith

Actually, my real application is a bit more complicated and it
does have the 'belongs_to :forum, :counter_cache => true ' in Topic
class.
Nevertheless the problem still exist because my main page should look
like this:

Forum1 NumOfTopicsinForum1 NumOfRepliesInForum1
Forum2 NumOfTopicsinForum2 NumOfRepliesInForum2
.....

With Your solution I can print out the NumOfTopicsinForum without an
additional
SQL query, but i can not print the NumOfRepliesInForum (as I don't
have posts_count field in
Forum class) and there are some other minor reasons for having posts
in the Forum class.

Additionally my real Post class belongs to 3 other classes so even if
your solution was ok the problem
with wacky counters remains. Basically, I have a feeling that the
solution to my problem is simple and
I'm just missing something obvious :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top