0

I'm trying to create simple geo-model with tree-structure with Rails4. Every region has one parent region and can have many children regions.

class Region < ActiveRecord::Base
has_many :regions, belongs_to :region, dependent: :destroy
end

Schema:

create_table "regions", force: true do |t|
  t.string   "name"
  t.string   "description"
  t.integer  "region_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Unfortunatelly, such code is not working. What should i do?

Pavel Tkackenko
  • 963
  • 7
  • 20

3 Answers3

1

I think, you are looking for a self join relationship. Try this :

class Region < ActiveRecord::Base
  has_many :child_regions, class_name "Region", foreign_key: "parent_id" dependent:   :destroy      
  belongs_to :parent, class_name: "Region"  
end

You should have a parent_id in your schema as well. Thanks

Rails Guy
  • 3,836
  • 1
  • 20
  • 18
0
class Region < ActiveRecord::Base
  has_many :regions, dependent: :destroy
  belongs_to :region
end

Of course you also need region_id integer column in your regions table.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
0

I assume that Rails4 works just as Rails3 in this case:

class Region < ActiveRecord::Base
    has_many   :regions, dependent: :destroy
    belongs_to :region
end

has_many and belongs_to are class/singleton methods of Region. Aa such you cannot use one of them as a parameter to the other method.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64