ActiveRecord가 단순한 has_many
, belongs_to
등보다 복잡한 연결을 처리하는 방법을 이해하려고합니다.ActiveRecord 모델의 복잡한 연결
예를 들어, 음악 작곡을 녹음하는 응용 프로그램을 고려해보십시오. 각 공연에는 장르가있는 밴드가 있습니다. 각 공연에는 또한 지역이있는 장소가 있습니다. (갑자기위한 매우 향수를 느끼기 시작 해요) MS 액세스의 거친 표기에서
이러한 관계는 같이 제시 될 것입니다이
1 ∞ 1 ∞ ∞ 1 ∞ 1
Genre ---- Band ---- Gig ---- Venue ---- Region
내가 예를 들어, 찾을 수 있도록하고 싶습니다
, 한 지역에서 연주 한 모든 밴드 또는 특정 장르를 개최하는 모든 장소.
이상적으로, 내 모델이 코드
class Genre
has_many :bands
has_many :gigs, :through => bands
has_many :venues, :through => :gigs, :uniq => true
has_many :regions, :through => :venues, :uniq => true
end
class Band
belongs_to :genre
has_many :gigs
has_many :venues, :through => :gigs, :uniq => true
has_many :regions, :through => :venues, :uniq => true
end
class Gig
belongs_to :genre, :through => :band
belongs_to :band
belongs_to :venue
belongs_to :region, :through => :venue
end
등 Venue
및 Region
에 포함됩니다. 일반적으로 하나 하나의 특정 -
그러나, 나는이 대신
class Genre
has_many :bands
has_many :gigs, :through => bands
has_many :venues, :finder_sql => "SELECT DISTINCT venues.* FROM venues " +
"INNER JOIN gigs ON venue.id = gig.venue_id " +
"INNER JOIN bands ON band.id = gig.band_id " +
"WHERE band.genre_id = #{id}"
# something even yuckier for regions
end
class Band
belongs_to :genre
has_many :gigs
has_many :venues, :through => :gigs, :uniq => true
# some more sql for regions
end
class Gig
delegate :genre, :to => :band
belongs_to :band
belongs_to :venue
delegate :region, :to => :venue
end
나는이 개 질문이 같은 것을 생산해야 할 것으로 보인다.
일반
:나는 꽤 자주 와서 일을하려고 무슨 생각했을 것이다. 내가 할 수있는 최선의 방법은 무엇인가, 아니면 내가 간과하고있는 것보다 훨씬 간단한 것이 있습니까?
특히 :
내가 실제로 가지고있는 것은 실제로 작동하지 않습니다! 두 번째 장르 모델의 #{id}
은 실제로 클래스의 ID를 반환합니다. (나는 생각한다). 그러나 이것은 작동하는 것 같다 here과 here
나는 이것이 오히려 서사시적인 질문이라는 것을 알고있다. 당신이 이것을 가지고 있다면 고맙다. 어떤 도움이라도 대단히 감사하겠습니다!