虽然有自己的意思

时间:2016-12-20 14:57:23

标签: ruby-on-rails has-many-through

我正在铁轨上开展一个迷宫项目,具有讽刺意味的是,我迷路了。到目前为止,我对模型之间的has_many_though关系很新,所以如果模型本身有很多东西呢?

基本上,每个Room都有很多Rooms。我创建了一个Tunnel模型来连接这些房间,以便通过隧道将房间连接到许多其他房间。但是在建立这些关系时会变得更加棘手。

class Room < ApplicationRecord

  has_many :tunnels
  has_many :rooms, through: :tunnels

end

我的隧道连接两个房间

class Tunnel < ApplicationRecord
  belongs_to :lemmin_room, :foreign_key => "room1_id"
  belongs_to :lemmin_room, :foreign_key => "room2_id"
end

Rails文档非常清楚当ModelA有很多Model B到ModelC,但我认为它没有提到ModelA = ModelB。

1 个答案:

答案 0 :(得分:0)

您需要定义两个具有不同名称的belongs_to关联,例如:

class Tunnel < ApplicationRecord
  belongs_to :lemmin_room_1, :foreign_key => "room1_id"
  belongs_to :lemmin_room_2, :foreign_key => "room2_id"
end

然后,在您的Room模型中:

class Room < ApplicationRecord
  has_many :tunnels
  has_many :rooms, through: :tunnels, source: :lemmin_room_1
end

您可以指定source以获取所需的房间Tunnel