Ruby-on-Rails: Multiple has_many :through possible?

Posted by williamjones on Stack Overflow See other posts from Stack Overflow or by williamjones
Published on 2010-03-04T23:23:26Z Indexed on 2010/03/24 8:33 UTC
Read the original article Hit count: 238

Is it possible to have multiple has_many :through relationships that pass through each other in Rails? I received the suggestion to do so as a solution for another question I posted, but have been unable to get it to work.

Friends are a cyclic association through a join table. The goal is to create a has_many :through for friends_comments, so I can take a User and do something like user.friends_comments to get all comments made by his friends in a single query.

class User
  has_many :friendships
  has_many :friends, 
           :through => :friendships,
           :conditions => "status = #{Friendship::FULL}"
  has_many :comments
  has_many :friends_comments, :through => :friends, :source => :comments
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end

This looks great, and makes sense, but isn't working for me. This is the error I'm getting in relevant part when I try to access a user's friends_comments:
ERROR: column users.user_id does not exist
: SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments".user_id = "users".id WHERE (("users".user_id = 1) AND ((status = 2)))

When I just enter user.friends, which works, this is the query it executes:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))

So it seems like it's entirely forgetting about the original has_many through friendship relationship, and then is inappropriately trying to use the User class as a join table.

Am I doing something wrong, or is this simply not possible?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about has-many-through