First the data model:
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.
What you’re looking for is a named scope in the Forum model.
The join can be greatly simplified by adding has_many :through relationships for your Comment and Reply models in the Forum model. But I can never remember how nested joins work out, so I’ve posted a solution that will work with what you’ve got.
Now…
Will return an array of forums where a user has posted a topic, reply or comment.
For a list of forums a particular user has posted in:
Assuming I got that right, this statement:
will return a list of users that have posted in forum either by topic, comment or reply.
P.S. it’s probably not a good idea to allow destruction of users in this model. The way you’ve laid things out, if a user is destroyed, any topics, replies or comments they posted will also be removed. Instead your users should be deactivated.