newbie needs help with associations


Newbie here. I'm having to enter this from memory since my work is on
a closed network, so forgive any syntax errors.

I'm trying to recreate some basic Google Plus functionality with
regards to users, posts, and circles - that is, a user can see a post
only if he/she is in one or more of the same circles that the post
belongs to:

class User
  has_and_belongs_to :circles
  has_many :posts
class Post
  has_and_belongs_to :circles
  belongs_to :user # the user that created the post
class Circle
  has_and_belongs_to :posts
  has_and_belongs_to :users

Given the above, how can I retrieve all posts viewable by a user?
The SQL (I think) would be:

select distinct
  from posts p, circles_posts cp, circles_users cu
  where = circles_posts.post_id
  and cp.circle_id = cu.circle_id
  and cu.user_id =

I also need to be able to retrieve posts related to a subset of
circles to which the user belongs:

select distinct
  from posts p, circles_posts cp, circles_users cu
  where = circles_posts.post_id
  and cp.circle_id = cu.circle_id
  and cu.circle_id in (4,5,6)
  and cu.user_id =

Can someone help? I can handle the basic RoR associations but this
one is making my brain explode. :slight_smile:

Thanks _very_ much,

Stan McFarland

Firstly each of those should be has_and_belongs_to_many, but I expect
you knew that.
Secondly, I don't know whether you realise, but I don't think the
above will fully model the google+ concept. I think you need to model
the asymmetric way that circles relate to users. I think you will
need two relationships, firstly user has_many circles and circle
belongs to user. This will map the fact that a user has a number of
circles. Then you need to record who is *in* that circle via a
has_and_belongs_to_many relationships, where you will need to use the
:class_name specifier. Something like
user has_and_belongs_to_many :member_of_circles, :class_name=>'Circle'
Then the circles owned by a user are
and the circles that the user is in are
You will also need the equivalent reverse relationship to get all the
users that are members of a circle.

I have not tested that, in fact I am not sure I have used :class_name
with a has_and_belongs_to relationship, I tend to prefer explicit join

If you are a beginner at Rails I think you might be better to start
with something simpler, this is a non-trivial problem for the
beginner. Have you worked through some good tutorials? I recommend which is free to use online. Make sure you are
using Rails 3 and that the tutorial is for Rails 3.

Also work through the Rails Guides.


Thanks for the feedback. You're right about the asymmetry of the circles- I'll work on that. I'd pick a simpler problem to solve but this is what my client is paying me for. I've actually built a few rails projects but they were really straightforward.

Thanks again