在Rails中,是否可能拥有多个互相通过has_many:through
关系的联系?我收到了这个建议作为我发表的另一个问题的解决方案,但一直无法使其正常工作。
朋友是通过一个连接表进行循环关联。目标是创建一个has_many:through
关于friends_comments
,这样我就可以通过单个查询获得某个User
的所有朋友的评论,比如使用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
我觉得这个方案很棒,也很有道理,但是对我来说还不起作用。当我尝试访问用户的好友评论时,我得到了以下相关部分的错误信息:
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类作为联接表。
我是否做错了什么,或者这根本不可能?
user.friends.comments
比user.friends_comments
更好。 - Harish Shettyfind_by
)和多行(find_all_by
)。find_all_by_user_id
是一种多行动态查找器。请阅读 Rails 文档以获取更多详细信息:http://guides.rubyonrails.org/active_record_querying.html#dynamic-finders - Harish Shetty