2011-12-20 80 views

回答

1

我发布此作为答案,因为我无法提供评论中的文档片段。瑞恩的解决方案需要调整。

foreign_key属性在has_many :through关联中被忽略。您应该使用source属性。

:通过

指定通过其来执行查询的关联。 这可以是任何其他类型的关联,包括其他:通过 关联。 选项:class_name,:primary_key和:foreign_key 将被忽略,因为关联使用源反射。

..

:源

指定通过的has_many 使用的源协会名称:查询。如果名称不能从 关联中推断出来,请使用它。 has_many:订阅者,:through =>:订阅将 寻找订阅者:订阅者订阅者,除非给出 :源。

以下解决方案应该工作:

class User < ActiveRecord::Base 
    has_many :fb_friend_cache 
    has_many :facebook_friends, :through => :fb_friend_cache, :source => :fb_user 
end 

class FbFriendCache < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :fb_user, :class_name=>"User" 
end 
2

您需要首先定义facebook_friends_cache协会:

has_many :facebook_friend_cache, :class_name => "FacebookFriendCache" 

然后,你需要在那之后定义:through协会:

has_many :fb_friends, :through => :facebook_friend_cache, :foreign_key => :user_id 

这里的foreign_key需要是代表现场外部表中User对象的ID,因此它需要是user_id而不是fb_user_id

我真的会给facebook_friend_cache一个更好的名字。

+0

将你的名字呢?我试了一下,模型实际上是“FbFriendCache”它的错误与无法找到关联:模型中的fb_friend_cache用户 – AnApprentice 2011-12-20 23:06:35

+1

您需要先定义:fb_friend_cache关联,然后再尝试在另一个关联中引用它。 – 2011-12-20 23:16:33

+0

瑞恩,是不是上面发生了什么? – AnApprentice 2011-12-20 23:26:31

相关问题