One table - two models

I have a hierarchical structure for the Board model (implemented using a family tree).

Instead of one model and some areas, I would like to have two models: Board for elements of the root level ( ancestry value of the nil column) and Category for the rest ( ancestry value of the column not nil ). They will use the same boards table.

How can I do something like this?

+7
ruby-on-rails ruby-on-rails-3
source share
2 answers

You can explain the specific table for the model using set_table_name or self.table_name depending on the version of your rail. You can also define a default scope for each query made for this model using default_scope , so the combination of both should be what you are looking for:

 class Category < AR:Base self.table_name = 'boards' default_scope where('boards.ancestry IS NOT NULL') end 
+10
source share

You can specify the name of the category model table and create a default scope:

 class Category < ActiveRecord::Base self.table_name = "boards" default_scope where('boards.ancestry IS NOT NULL') end 

And you should be able to interact with both models with table tables.

Or you stay with one model and add two modules for a specific material. It depends on your preference.

+3
source share

All Articles