有可能在Rails中有多个相互传递的has_many :through
个关系吗?我收到了这样做的建议,作为我发布的另一个问题的解决方案,但一直无法让它发挥作用.
朋友是一个通过连接表的cyclic association.我可以用user.friends_comments
条来创建一个简单的查询,比如说我可以用friends_comments
条来创建一个has_many :through
条 comments .
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)))
因此,它似乎完全忘记了最初的has_many
-through-friendly关系,然后不恰当地try 将User类用作连接表.
是我做错了什么,还是这根本不可能?