2016-06-29 1 views
1

:를 통해 연결 :레일 : 추종자에 대한 테이블을 통해 has_many, 다음 나는 사용자 모델을 가지고 있고 사용자가 많은 추종자와 다음이

has_many :connections 
has_many :followers, :through => :connections, :foreign_key => :follower_id, :source => :user, class_name: User 
has_many :following, :through => :connections, :foreign_key => :user_id, :source => :user, class_name: User 

내 연결 테이블 (사용자가 준수되고)는 USER_ID를 가지고 있으며, follower_id을 (다음 사용자).

나는 새로운 연결을 만들 수 있습니다

Connection.create(user_id: 1, follower_id: 500) 

내가 연결이 생성 된 것을 볼을 아직 나는 각각의 사용자에서이 액세스 할 수 없습니다 :

u = User.find(1) 
u.followers => [] 
u.following => [] 

u = User.find(500) 
u.followers => [] 
u.following => [] 

어디서 잘못된 것입니까?

답변

0

첫 번째 관계에서는 소스가 :user 인 반면 :follower이어야합니다.

나중에 편집

:

위의 수정 한 문제가 있지만 완전한 해결책이 많은 연결이 필요합니다 다음에 대한 follwers에 대한 하나 하나를 다음과 같이

class User < ActiveRecord::Base 
    has_many :followers_connections, foreign_key: :user_id, class_name: "Connection" 
    has_many :following_connections, foreign_key: :follower_id, class_name: "Connection" 
    has_many :followers, through: :followers_connections, class_name: "User", source: :follower 
    has_many :following, through: :following_connections, class_name: "User", source: :user 
end 


class Connection < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :follower, class_name: "User" 
end 


# create some sample data 
5.times { User.create } 
Connection.create user_id: 1, follower_id: 2 
Connection.create user_id: 1, follower_id: 3 
Connection.create user_id: 4, follower_id: 1 
Connection.create user_id: 5, follower_id: 1 

# get followers 
User.find(1).followers.pluck(:id) => [2, 3] 
# SQL run: SELECT "users"."id" FROM "users" INNER JOIN "connections" ON "users"."id" = "connections"."follower_id" WHERE "connections"."user_id" = ? [["user_id", 1]] 

# get following 
User.find(1).following.pluck(:id) => [4, 5] 
# SQL run: SELECT "users"."id" FROM "users" INNER JOIN "connections" ON "users"."id" = "connections"."user_id" WHERE "connections"."follower_id" = ? [["follower_id", 1]] 
+0

최고 - 즉 u.followers 작업,하지만 여전히 U에 대한 빈 보여주는 것.수행원. 왜 그런가? –

+0

사용자 1이 사용자 2를 따라 시작합니다. user1.following ==> []를 호출하면됩니다. user2.following ==> [user2] –

+0

연결에 2 개의 has_many 관계가 필요합니다. 위의 예를 몇 분 안에 게시하십시오. – bcd

0

업데이트 협회, 그들은해야 당신을 위해 일합니다.

has_many :connections 
has_many :followers, through: :connections, class: 'User' 
has_many :following, through: :connections, foreign_key: :follower_id, source: :user 

설명 :
1) 당신은 연결 통해 사용자 has_many 추종자, connections 테이블에 user_id을 기대
레일을 말할 때. 우리의 경우에는 user_idconnections입니다.
레일은 연결시 follower_id이 필요합니다. 우리의 경우에 우리는 연결에 follower_id 있습니다. 그러나 여기서 follower_id 레일즈는 모델로 follower을 유추합니다, 우리는 어떤 모델 이름도 가지고 있지 않습니다 follower. 따라서 followers을 검색하는 데 사용할 class: 'User'을 언급해야합니다.

2) 사용자 has_many가 연결을 통해 다음과 같은 말을 connections 테이블에 user_id을 기대
레일. 우리의 경우에 연결에 user_id이 있지만 우리는 following을 검색하기 위해이 user_id를 사용하고 싶지 않습니다. following을 검색하려면 follower_id이 필요하므로 foreign_key: :follower_id을 언급해야합니다. 따라서 레일스는 follower_id을 외래 키로 사용합니다.
레일following_idconnections 테이블이 있어야합니다. 우리의 경우 우리는 following_idconnections 테이블에 가지고 있지 않습니다. 따라서 우리는 source: :user을 언급 할 필요가 있습니다.이 레일즈는 유효한 User 모델을 기대하고 있습니다.

출처 : http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

관련 문제