0

私はルート内の場所を関連づけたい:1つのルートは2つの場所(開始ポイントと終了ポイント)+これらの2つのポイントを距離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

ルートは開始地点と終了地点の2つに関連付ける必要があります。

だから一つの選択肢は次のようになります。

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 

しかし、あなたのルートは、開始と終了の場所の正式な概念を持っていない場合 - つまり、彼らはちょうど2つの場所に参加する - あなたは中間から利益を得ることができますモデル:この文脈において

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として解釈されるべきです。

これにより、特定の場所で終了するすべてのルートを「開始」または「終了」というコンセプトなしに、より簡単に見つけることができます。

関連する問題