2016-08-11 6 views
2

다음과 같이 내가 설정 3 개 모델을 가지고 :은 반환이 불가능 SQL을 통해 has_many 가입 다형성 레일

class User < ActiveRecord::Base 

    has_many :interests, as: :interesting, dependent: :destroy 
    has_many :games, through: :interests, source: :interesting, source_type: 'Game' 
    has_many :people, through: :interests, source: :interesting, source_type: 'Person' 

end 

class Interest < ActiveRecord::Base 

    belongs_to :interesting, polymorphic: true 
    validates :user_id, presence: true 
    validates :interesting_id, presence: true 
end 

class Game < ActiveRecord::Base 
    has_many :users, through: :interests 
    has_many :interests, as: :interesting 
end 

class Person < ActiveRecord::Base 

    has_many :users, through: :interests 
    has_many :interests, as: :interesting 

end 

나는 데이터베이스에 대한 SQL 실행이 너무 분명

SELECT "games".* FROM "games" 
INNER JOIN "interests" 
ON "game"."id" = "interests"."interesting_id" 
WHERE "interests"."interesting_id" = $1 AND 
    "interests"."interesting_type" = $2 AND 
    "interests"."interesting_type" = $3 
[["interesting_id", 3], 
["interesting_type", "User"], 
["interesting_type", "Game"]] 

입니다 user.games를 호출 할 때 아무것도 반환되지 않습니다. ["interesting_type", "User"]이 포함되어 있지 않으면 쿼리가 작동합니다.

내가 뭘 잘못하고 있니? User 클래스와 GamePerson 클래스를 설정하는 가장 좋은 방법은 무엇입니까?

나는

+0

당신은 당신의 pr 오렘? –

답변

1

:id:, :interesting_id, :interesting_type을해야하는 테이블 _ interests

class User < ActiveRecord::Base 

    has_many :interests, dependent: :destroy 
    has_many :games, as: :interesting, through: :interests, source_type: 'Game' 
    has_many :people, as: :interesting, through: :interests, source_type: 'Person' 

end 

class Interest < ActiveRecord::Base 

    belongs_to :interesting, polymorphic: true 
    validates :user_id, presence: true # I don't know the reason to use that if you use as polymorphic 
    validates :interesting_id, presence: true 
end 

을 시도하는 다음의 작업 표시하십시오 v4.2.6 레일을 사용하고 있습니다 이 사용 사례 :

User < ActiveRecord::Base 
    has_many :interests, dependent: :destroy 
    has_many :games, through: :interests, 
      source: :interesting, source_type: 'Game' 
    has_many :people, through: :interests, 
      source: :interesting, source_type: 'Person' 

end 

class Interest < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :interesting, polymorphic: true 
    validates :user_id, presence: true 
    validates :interesting_id, presence: true 
end 
0

이 요약하는 속성 만 그래서

+0

테스트 중이지만 제대로 작동하는 것 같습니다. 사용자 akoller

+0

또한 관심사 belongs_to 사용자 및 게임 has_many : users처럼 : : 흥미 롭다 : : 관심사 – akoller

+0

@akoller 문제 해결을 마쳤습니까? –