내 앱에는 도시에 여러 링크가있을 수 있습니다. 링크는 두 도시를 연결하며 양방향입니다. 결과적으로 링크에는 '보낸 사람'과 '가는 사람'이 없습니다. 이것은 다음과 같은 db schema
결과 : 내 액티브 모델에서has_many 관계가 두 개의 외래 키
create_table "links", force: true do |t|
t.integer "endpoint1_id"
t.integer "endpoint2_id"
t.integer "capacity"
end
create_table "cities", force: true do |t|
t.string "name"
t.string "lat"
t.string "long"
end
, 나는 두 테이블 사이의 관계를 선언합니다. 나는 has_many
관계를 설정할 때 두 개의 외래 키를 선언 할 수없는 것 때문에, 나는 이렇게 그 주위에 일 : City.find(1).links
을하지만 적절한 솔루션을하지 보인다 및 상속을 적용하지 않습니다 :이 날을 수행 할 수 있습니다
class City < ActiveRecord::Base
# has_many with two foreign keys?
# has_many :links
def links
Link.where("endpoint1_id=? OR links.endpoint2_id=?", id, id)
end
end
class Link < ActiveRecord::Base
belongs_to :endpoint1, :class_name => 'City'
belongs_to :endpoint2, :class_name => 'City'
end
. 또한 link
에서 city.endpoint1
과 city.endpoint2
을 모두 통과하지 않으면 관련 도시를 찾을 수 없습니다.
두 개의 외래 키와 has_many
관계를 정의하는 더 좋은 해결책이 있습니까? 아니면이 접근법을 벗어나서 어쨌든 db schema
을 변경해야합니까?
질문의 첫 번째 줄을 다시 쓸 수 있습니까? 도시가 많은 연결 고리를 가지고 있고 도시 - 연결 도시 연결을 원하십니까? – kirqe
어쩌면 당신은'has_many : links_to'와'has_many : links_from'와 같은'has_many' 세트에 대해 작업 할 수 있습니다. 그리고 지금 당신이하고있는 일을 더 많거나 적게합니까? – Albin