问题
I have model Offer
with many fields, among which are there are two fields that relate to the same model:
# == 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
and arrival_port_id
relate to the same model Port
, but can be also NULL
, if no departure or arrival port provided.
How should Offer
and Port
models look like in this case?
回答1:
Something like this:
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
来源:https://stackoverflow.com/questions/27051450/rails-activerecord-model-has-one-twice-to-the-same-model-with-different-foreign