Rails ActiveRecord model has_one twice to the same model with different foreign keys

前提是你 提交于 2019-12-08 12:25:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!