has_many of itself though

253 Views Asked by At

I'm working on a maze project in rails, and ironically, I got lost. So far, I'm pretty new with has_many_though relationships between models, so what if a model has many of itself through something ?

Basically, Each Room has many Rooms. I created a Tunnel model to connect these rooms, so that a room is connected to many others through tunnels. But it gets trickier when it comes to building these relations.

class Room < ApplicationRecord

  has_many :tunnels
  has_many :rooms, through: :tunnels

end

And my Tunnel gets to connect two rooms

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

Rails documentation is pretty clear when it comes toe ModelA has many Model B through ModelC, but I don't think it ever mentions ModelA = ModelB.

1

There are 1 best solutions below

0
On

You need to define two belongs_to association with different name, like:

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

Then, in your Room model:

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

You can specify source to get what rooms you want in Tunnel.