Update counter cache for 2 models

Let's say I have the following models:

User, has_many :messages, :topics Forum, has_many :topics Topic, belongs_to :user, has_many :messages Message, belongs_to :user, :topic

How to tell both User and Topic, that a new Message has been created?

I can do: @user.messages << @message, but what to do to notify the @topic? Is it possible to do that in a pretty manner?

Crap, after doing some tests it appears, that Rails needs to refetch the user and topic objects from DB before updating their count columns.

Create an observer for the message model and do your updates.

Let's say I have the following models:

User, has_many :messages, :topics Forum, has_many :topics Topic, belongs_to :user, has_many :messages

Topic is missing a belongs_to :Forum

Message, belongs_to :user, :topic

How to tell both User and Topic, that a new Message has been created?

I can do: @user.messages << @message, but what to do to notify the @topic? Is it possible to do that in a pretty manner?

Can you not just do @topic.messages << @message

Are you sure you have your relationships right? For example does the topic that a message belongs to also belong to the same user? If so then for user you want has_many through on one of them, through the other.

Colin

Can you not just do @topic.messages << @message

then the message is missing the user_id.

A found a way:

message = user.messages.build(:content => 'blabla') topic.messages << message.

But to update the counter columns, then rails does 2 redundant select queries: one for topic and one for user then updates the counter columns, although user and topic objects are already available.

I could code that manually but it doesn't look pretty. I think some time ago Fred Cheung said that intelligent reserve associations would be available in Rails 3, for now rails has to do redundant selects in order to update the objects. Maybe there is another and better way to achieve what I want?