1

이 작업을 수행하는 방법을 알 수 없습니다. 나는 this onethis one을 포함하여 다른 질문을 보았지만 아무 소용이 없습니다. 여기 레일 has_many : through : STI를 사용하는 테이블에 연결

내 모델입니다 :

class User < ActiveRecord::Base 
    has_many :connections 
    has_many :data_sources, through: :connections 
end 

class Connection < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :data_source 
end 

class DataSource < ActiveRecord::Base 
    has_many :connections 
    has_many :users, through: :connections 
end 

class AdNetwork < DataSource 
end 

class Marketplace < DataSource 
end 

AdNetwork은 마켓 플레이스 및 데이터 소스 모두 STI를 통해 동일한 테이블을 사용합니다.

내가 돌아 User라는 marketplacesad_networks에 연결을 설정하려는 모든 type 각각 MarketPlace 또는 AdNetwork입니다 data_sources. 어떻게해야합니까?


것들 내가 작동하지 않았다 시도했다 :

class User 
    has_many :marketplaces, through: :data_sources # Throws an error 
    has_many :marketplaces, through: :connections # Throws an error 
    has_many :marketplaces, through: :connections, source: :data_source # Returns ALL data sources, not just Marketplaces 
    has_many :marketplaces, { through: :connections, source: :data_source }, -> { where(type: "Marketplace" } # Again this returns ALL data sources. Wtf??? 
end 

가 나는 또한 Connection에 열 data_source_type를 추가하고 다음 줄을

클래스 연결 belongs_to를 추가하는 시도 : data_source, 다형성 : true
end

클래스 데이터 소스 has_many :로 연결 : DATA_SOURCE 끝

클래스 사용자 has_many : 마켓 플레이스를 통해 : 연결 소스 : DATA_SOURCE, SOURCE_TYPE "마켓 플레이스" 끝

... 그러나 지금은 #marketplaces 빈 관계를 반환합니다. (마켓 플레이스 또는 AdNetwork를 추가해도 은 DataSource으로 설정되어 있습니다.)

내가 뭘 잘못하고 있니?

답변

0

비슷한 작업을하고 있습니다. 그 대답은 당신의 모델 속성에 있다고 생각합니다.

내 연결 테이블에서 참조 ID를 생략했다는 것을 깨달았을 때이를 해결했습니다 (연결 테이블과 비슷 함).

참조 참조 : http://guides.rubyonrails.org/association_basics.html#the-has-one-through-association

혹시 해결책을 찾았나요?

+3

[도움말 센터] (http://stackoverflow.com/)에서 "링크에 대한 컨텍스트 제공"및 "대상 사이트에 연결할 수 없거나 영구적으로 오프라인 상태가되는 경우 중요한 링크의 가장 중요한 부분을 항상 인용합니다." 도움/방법에 대한 답변) – mkobit

관련 문제