Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top