0

경로 내의 장소를 연결하고 싶습니다. 하나의 경로에 두 개의 위치가 있습니다. (시작점과 종점) +이 두 점을 거리 btw만큼 저장해야합니다. 데이터 모델이 올바른지 궁금합니다. https://github.com/roms182/frais-kilometriques/blob/master/Annexes/shortmodel.pngActiveRecord : 장소와 경로에 대한 연관성은 무엇입니까?

그리고 Rails에서 연결을 정리하는 방법을 모르겠습니다.

class Place < ApplicationRecord 
    has_many :routes 
end 

class Route < ApplicationRecord 
    belongs_to :place 
end 

답변

1

경로는 시작 지점과 끝 지점과 연결되어야합니다.

그래서 하나의 옵션은 다음과 같습니다

class Place < ApplicationRecord 
    has_many :routes_as_start, class_name: "Route", foreign_key: :start_place_id 
    has_many :routes_as_end, class_name: "Route", foreign_key: :end_place_id 
end 

class Route < ApplicationRecord 
    belongs_to :start_place, class_name: "Place" 
    belongs_to :end_place, class_name: "Place" 
end 

그러나, 당신의 경로는 시작과 끝 장소의 공식적인 개념이없는 경우 - 즉, 그들은 단지 두 곳에 가입 - 당신은 중간 혜택을 누릴 수 있습니다 모델 : 이러한 맥락에서

class Place < ApplicationRecord 
    has_many :route_ends, 
    has_many :routes, through: :ends 
end 

class RouteEnd 
    belongs_to :place 
    belongs_to :route 
end 

class Route < ApplicationRecord 
    has_many :route_ends 
    has_many :places, :through :route_end 
end 

:has_many 정말 :has_two로 해석되어야한다.

이렇게하면 "시작"또는 "끝"이라는 개념없이 특정 장소에서 끝나는 모든 경로를보다 쉽게 ​​찾을 수 있습니다.

관련 문제