Ruby-On-Rails 中的两个一对多关系

Two one-to-many relationships in Ruby-On-Rails

我在 Rails 中有 2 个模型,每个路径都有一个 To 字段和一个 From 字段,这两个字段都引用 Location Id,但我似乎无法正确设置关系。任何帮助,将不胜感激。我正在使用 Rails 4.2.6.

class Location < ActiveRecord::Base
    #Fields - id, name, description, latitude, longitude

end

class Path < ActiveRecord::Base
    #Fields - id, from, to, distance

    # belongs_to :from_location, class_name: 'Location', foreign_key: 'from'
    # belongs_to :to_location, class_name: 'Location', foreign_key: 'to'

    # belongs_to :from_location, class_name: 'Location'
    # belongs_to :to_location, class_name: 'Location'
end

假设您的 'from' 和 'to' 字段是包含位置 ID 的整数,您应该能够执行以下操作:

class Path < ActiveRecord::Base
  belongs_to :from_location, class_name: 'Location', foreign_key: 'from'
  belongs_to :to_location, class_name: 'Location', foreign_key: 'to'
end

然后对于路径记录,您应该能够调用 .from_location 和 .to_location 来获取位置。

阅读 this 了解更多信息。