ActiveRecord가 찾고있는 관련 열을 알려줘야합니다. 나는 다음과 같은 갖고 싶어 같은데요 :
class Person < ActiveRecord::Base
has_many :connection_bindings
has_many :companies, :through => :connection_bindings
has_many :people, :through => :connection_bindings
end
class company < ActiveRecord::Base
has_many :connection_bindings
has_many :companies, :through => :connection_bindings
has_many :people, :through => :connection_bindings
end
문제는 두 테이블이 하나 개의 컬럼에서이 ID를 넣고 레일이 조회하는 테이블 모른다 가지고있다.
예를 들어 데이터베이스의 모든 connection_binding 행에서 connect_from은 company_id 또는 person_id가 될 수 있으며 connect_to도 마찬가지입니다. 그래서 당신은 '안녕 레일, 내 연결된 ConnectionBindings'로드 및 connect_from 11 및 connect_to 12 행을 가져옵니다. 그러나 그것은 Person.find (12) 또는 Company.find (12)합니까? 말할 방법이 없습니다!
class Person < ActiveRecord::Base
has_many :connection_bindings
has_many :person_connections, :through => :connection_bindings, :source => :to_connect, :source_type => 'Person'
has_many :company_connections, :through => :connection_bindings, :source => :to_connect, :source_type => 'Company
def connections
person_connections + company_connections
end
end
당신은 다른 측면에서 그를 구축해야합니다 (물론 관련 : from_connect의)
대신 레일 좀 더 많은 정보를 제공해야하지만, 그 방법에 따라 달라집니다 이 연결을 사용하고 있습니다. 당신을 시작할 수있을만큼 충분해야합니다.
Ruby와 Rails의 마법의 세계에서 익숙한 것보다 훨씬 더 많은 타이핑을하지만, 매우 복잡한 데이터 패턴으로 구성하려고합니다. 그것이 불가능하다는 것을 의미하지는 않습니다. 레일스는 훌륭한 프레임 워크로서 여러분이 정말로 원하는 것을하지 못하게 할 것입니다. 그러나 여러분의 목적을 명확하게 설명하는 것은 드문 일입니다.
고맙습니다. 대답은 매우 도움이되었습니다. 나는 다음 답에서 나를 위해 실제 해결책을 적었다. – RunFor