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? -- Posted via http://www.ruby-forum.com/.
Crap, after doing some tests it appears, that Rails needs to refetch the user and topic objects from DB before updating their count columns. -- Posted via http://www.ruby-forum.com/.
Create an observer for the message model and do your updates. On Sep 29, 12:59 pm, Fernando Perez <rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:> 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? > -- > Posted viahttp://www.ruby-forum.com/.
Mukund wrote:> Create an observer for the message model and do your updates. >It doesn''t work either. Inside the observer method, I won''t have access to @user and @topic. -- Posted via http://www.ruby-forum.com/.
2009/9/29 Fernando Perez <rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>:> > Let''s say I have the following models: > > User, has_many :messages, :topics > Forum, has_many :topics > Topic, belongs_to :user, has_many :messagesTopic 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? -- Posted via http://www.ruby-forum.com/.