Rails ActiveRecord模型has_one两次到具有不同外键的相同模型

时间:2014-11-20 23:17:05

标签: ruby-on-rails ruby rails-activerecord

我的模型Offer包含许多字段,其中有两个与同一模型相关的字段:

# == Schema Information
#
# Table name: offers
#
#  id                   :integer          not null, primary key
#  name                 :string(250)      default(""), not null
#  destination_id       :integer          not null
#  cruise_line_id       :integer          not null
#  ship_id              :integer          not null
#  departure_date       :date             not null
#  departure_port_id    :integer
#  arrival_date         :date             not null
#  arrival_port_id      :integer

departure_port_idarrival_port_id与同一型号Port相关,但如果没有提供出发或到达港口,也可以NULL

在这种情况下,OfferPort模型应该如何?

1 个答案:

答案 0 :(得分:0)

这样的事情:

class Offer < ActiveRecord::Base
  belongs_to :departure_port, class_name: "Port", foreign_key: "departure_port_id"
  belongs_to :arrival_port, class_name: "Port", foreign_key: "arrival_port_id"
end

class Port < ActiveRecord::Base
  has_one :offer
end