초기 단계부터 다형성에 대한 지원이 크게 향상되었습니다. 관계 모델 인 모든 모델에 대해 단일 조인 테이블을 사용하여 Rails 2.3에서이 작업을 수행 할 수 있어야합니다.
class Relation
belongs_to :owner, :polymorphic => true
belongs_to :child_item, :polymorphic => true
end
class Book
has_many :pwned_relations, :as => :owner, :class_name => 'Relation'
has_many :pwning_relations, :as => :child_item, :class_name => 'Relation'
# and so on for each type of relation
has_many :pwned_movies, :through => :pwned_relations,
:source => :child_item, :source_type => 'Movie'
has_many :pwning_movies, :through => :pwning_relations,
:source => :owner, :source_type => 'Movie'
end
이런 종류의 데이터 구조의 결점은 평등 한 쌍이 될 수있는 두 가지 역할을 만들어야한다는 것입니다. 내 책에 대한 모든 관련 영화를보고 싶은 경우에, 나는 함께 세트를 추가해야합니다 :
(pwned_movies + pwning_movies).uniq
이 문제의 일반적인 예는 소셜 네트워킹 응용 프로그램에서 "친구"관계이다. Insoshi가 사용하는 한 가지 솔루션은 반대 모델을 생성하는 조인 모델 (이 경우 Relation
)에 after_create
콜백을 등록하는 것입니다. after_destroy
콜백도 비슷하게 필요하지만 이와 같은 방식으로 일부 추가 DB 스토리지 비용으로 단일 DB 쿼리에 관련된 모든 영화를 얻을 수 있다고 확신 할 수 있습니다.
class Relation
after_create do
unless Relation.first :conditions =>
[ 'owner_id = ? and owner_type = ? and child_item_id = ? and child_item_type = ?', child_item_id, child_item_type, owner_id, owner_type ]
Relation.create :owner => child_item, :child_item => owner
end
end
end
이 단지를했다 당신이 당신의 항목 테이블 유형을 넣어 있는지 확인 선언 어떤 경우
얼마나 closesly 관련 영화/책에 따라 예. 내 실제 데이터 모델에는 이러한 정확한 내용이 없지만 그 중 많은 부분이 있습니다. 결국이 길로 가면 여럿이 조인 테이블을 보게됩니다. –
Yikes ... 잡았다. 좀 더 생각해 볼게. – fig