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.
You need to define two
belongs_to
association with different name, like:Then, in your
Room
model:You can specify
source
to get what rooms you want inTunnel
.