문제

다음 엔티티가 있습니다.

  • 사용자
  • 회사
  • 조직

사용자는 사용자, 회사, 조직 및 미래 파티 객체를 친구 목록에 추가 할 수 있어야합니다.

저의 원래 아이디어는 친구와의 다형성 관계가있는 우정 대상을 사용하는 것과 관련이있었습니다.

단순화 된 우정 스키마 :

  • user_id
  • friendable_id
  • friendable_type
User
- has_many :businesses, :through => :friendships, :conditions => ['friendable_type=?', 'Business'], :source => :friendable

내 문제는 Ruby on Rails Activerecord가 조인 테이블의 다형성 관계를 통해 관계를 통해 has_many를 지원하지 않는다는 것입니다.

결국 나는 모든 유형, 특정 유형 등의 친구 목록을 얻기 위해 반복 할 수있는 단일 조인 테이블을 갖고 싶습니다.

john = User.find(5)
john.friendships.map {|friendship| friendship.friendable }
john.businesses (has_many :through scoped to only the businesses)
john.organizations (has_many :through scoped only to the organizations)

나는 사용자, 비즈니스 및 조직이 일반 파티 클래스에서 상속하고 협회가 기본 파티 클래스를 가리 키게하는 것을 고려했지만, ORM의 맥락에서 많은 정크 필드로 이어지는 경우 더러워 보입니다.

내가 알고 싶은 것은 다른 사람들 이이 오류를 피하면서 ActiveRecord를 사용하여 공통 조인 테이블을 통해 유사한 개체와 일대일 관계를 만들고 싶은 상황에 어떻게 접근 할 것인지입니다. :)

Cannot have a has_many :through association 'User#businesses' on the polymorphic object 'Friendship#friendable'.

모든 조언은 크게 감사했습니다.

감사!

도움이 되었습니까?

해결책 2

Rails 플러그인 'has_many_polymorphs'를 사용하면 내가 원하는 것을 정확하게 수행 할 수 있습니다.

http://github.com/fauna/has_many_polymorphs/tree/master

이 라인을 사용자 모델에 추가하면 원하는 기능을 제공했습니다.

has_many_polymorphs :friendables, :from => [:businesses, :organizations], :through => :friendships

다른 팁

사용하지 않음 : Througe, 사용 : AS => 다형성 has_many 관계에서 대신 친절합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top