Implementing the tree with reference to the root for each leaf
Posted
by AntonAL
on Stack Overflow
See other posts from Stack Overflow
or by AntonAL
Published on 2010-05-20T15:49:54Z
Indexed on
2010/05/23
1:30 UTC
Read the original article
Hit count: 408
Hi, i implementing a products catalog, that looks, like this:
group 1
subgroup 1
subgroup 2
item 1
item 2
...
item n
...
subgroup n
group 2
subgroup 1
...
subgroup n
group 3
...
group n
The Models:
class CatalogGroup < ActiveRecord::Base
has_many: catalog_items
has_many :catalog_items_all, :class_name => "CatalogItem", :foreign_key => "catalog_root_group_id"
end
class CatalogItem < ActiveRecord::Base
belongs_to :catalog_group
belongs_to :catalog_root_group, :class_name => "CatalogGroup"
end
Migrations:
class CreateCatalogItems < ActiveRecord::Migration
def self.up
create_table :catalog_items do |t|
t.integer :catalog_group_id
t.integer :catalog_root_group_id
t.string :code
t.timestamps
end
end
For convenience, i referenced each CatalogItem to it's top-most CatalogGroup and named this association "catalog_root_group".
This will give us the simple implementation of search request, like "show me all items in group 1".
We will have a deal only with CatalogModel.catalog_root_group
The problem is - this association does't work. I always get "catalog_root_group" equals to nil
Also, i have tried to overcome the using of reference to root group ("catalog_root_group"), but i cannot construct appropriate search request in ruby ...
Do you know, how to do it ?
© Stack Overflow or respective owner