Has_many, through with multiple nested models?

First the data model, then the question:

running Rails 2.2.3, I have

class Forum < ActiveRecord::Base
has_many :topics, :dependent
=> :destroy, :order => ‘created_at
desc’
end

class User < ActiveRecord::Base
has_many :topics, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :replies, :dependent => :destroy
end

class Topic < ActiveRecord::Base
belongs_to :forum
belongs_to :user
has_many :comments, :dependent => :destroy
end

class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :topic
has_many :replies, :dependent => :destroy
end

class Reply < ActiveRecord::Base
belongs_to :user
belongs_to :comment
end

So Users can post Topics to Forums. They can also post Comments to the
Topics in a Forum. And they can post Replies to the Comments.

I want to be able to get a list of Forums they’ve participated in by
posting either Topics or Comments or Replies.

I could just create a Membership that would relate a User to a Forum
whenever they post something, but then I’d need to maintain the
Membership when/if they delete their last Post/Comment/Reply from a
given Forum. That seems messy.

what I’m wonder is if I can do something like this:

class User < ActiveRecord::Base
has_many :topics, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :replies, :dependent => :destroy

    has_many                :forums, :through => :topics, :uniq =>

true
has_many :forums, :through => :comments, :uniq
=> true
has_many :forums, :through => :replies, :uniq
=> true

end

I dont think so… Only the Topic model is directly associated with
the Forum.

Is there a clean way to do a HMT association on multiple, nested
associations like this?

Since topic, comment and reply are sharing a lot of the same fields as
well as some logic, I reckon I’d make a superclass here for the three of
them.
Topic, comment and reply are basically the same thing, right? A post.

By using a superclass you can base logic like finding which forums a
user has topics, comments and replies in off of User.posts.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs