Search code examples
ruby-on-rails-5nested-attributes

Class with nested association to itself


I have a class with a nested association to itself:

class Location < ActiveRecord::Base
  has_many :location_gateways
  has_many :gateways, through: :location_gateways, class_name: "Location", :dependent => :destroy 
  accepts_nested_attributes_for :gateways, reject_if: :all_blank, allow_destroy: true
  belongs_to :location, optional: true
end

The connecting model:

class LocationGateway < ActiveRecord::Base
  belongs_to :location, :class_name => "Location"
  belongs_to :gateway, :class_name => "Location"
end

Now I would like to make a form that can create a Location and some gateways but I get an Gateway must exist error when I submit it (the call to Location.new)

I'm assuming this is because the model Gateway doesn't exist. How can I make rails understand that it should create another Locationand not a Gateway?


Solution

  • Found no way around this error. I had to make a new class Gateway that inherits from Location and add a type to Locations (STI).