Rails ActiveRecord 模型 has_one 两次到具有不同外键的同一模型 [英] Rails ActiveRecord model has_one twice to the same model with different foreign keys
本文介绍了Rails ActiveRecord 模型 has_one 两次到具有不同外键的同一模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型 Offer
有很多字段,其中有两个字段与同一个模型相关:
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
和arrival_port_id
属于同一个型号Port
,但也可以是NULL
,如果没有出发或提供到达港口.
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.
Offer
和 Port
模型在这种情况下应该是什么样子的?
How should Offer
and Port
models look like in this case?
推荐答案
是这样的:
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
这篇关于Rails ActiveRecord 模型 has_one 两次到具有不同外键的同一模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文