代码之家  ›  专栏  ›  技术社区  ›  romss182

ActiveRecord:地点和路线有哪些关联?

  •  0
  • romss182  · 技术社区  · 7 年前

    我想关联路线中的位置:一条路线有两个位置(起点和终点)+我需要存储距离btw这两个点。我想知道数据模型是否正确: https://github.com/roms182/frais-kilometriques/blob/master/Annexes/shortmodel.png

    我不知道如何解决Rails中的关联。

    class Place < ApplicationRecord
      has_many :routes
    end
    
    class Route < ApplicationRecord
      belongs_to :place
    end
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   David Aldridge    7 年前

    你的路线需要与两个地方相关联——起点和终点。

    因此,一种选择是:

    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

    这使您可以更轻松地找到在特定位置终止的所有路线,而不必考虑它们是“起点”或“终点”。