You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:45