在 Rails 中是否可以有多个has_many :through
相互传递的关系?我收到了这样做的建议,作为我发布的另一个问题的解决方案,但一直无法让它发挥作用。
朋友是通过连接表的循环关联。目标是创建一个has_many :through
for friends_comments
,所以我可以采取 aUser
并做一些类似的事情user.friends_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
这看起来很棒,也很有意义,但对我不起作用。这是我在尝试访问用户的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)))
当我输入 user.friends 时,它可以工作,这是它执行的查询:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))
所以它似乎完全忘记了原来的has_many
通过友谊关系,然后不恰当地试图将User类用作连接表。
我做错了什么,或者这根本不可能?