我在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
答案 0 :(得分:0)
假设您的'from'和'to'字段是包含location 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
然后,对于Path记录,您应该能够调用.from_location和.to_location来获取位置。
阅读this以获取更多信息。