Rails ActiveRecord模型has_one两次到具有不同外键的相同模型
我有很多字段的模型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_id
和arrival_port_id
与同一型号的Port
,但如果没有提供出发或到达端口,也可以为NULL
。
在这种情况下, Offer
和Port
模型应该如何?
像这样的东西:
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