Rails中Address的Origin与Destination的has_many :through关联实现
完善后的关联配置
首先需要明确:Address 作为 Origin 和 Destination 之间多对多关联的中间表,需要配置对应的归属关联。同时原代码中 Origin 和 Destination 的关联逻辑存在错误,需一并修正:
class Address belongs_to :origin belongs_to :destination end class Origin has_many :addresses has_many :destinations, through: :addresses end class Destination has_many :addresses has_many :origins, through: :addresses end
关键说明:
Address表需要包含两个外键字段:origin_id和destination_id(分别对应Origin和Destination模型的主键)- 原代码中
Origin和Destination的关联逻辑存在顺序错误,正确的写法是先声明与中间表addresses的关联,再通过该中间表关联对方模型
内容的提问来源于stack exchange,提问作者listenlight
相关产品推荐
相关产品推荐

