Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One table - two models

I have hierarchical structure for model Board (implemented using ancestry gem).

Instead of one model and some scopes, I'd like to have two models: Board for root level elements (ancestry column value is nil), and Category for the rest(ancestry column value is not nil). They would be using the same table boards.

How can I do something like this?

like image 995
Marcin Doliwa Avatar asked Aug 19 '13 14:08

Marcin Doliwa


Video Answer


2 Answers

You could specify the table name of the category model and generate 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 wit the boards-Table.

Or you stay with one model and add two modules for the specific stuff. That depends on your preferences.

like image 180
Matthias Avatar answered Oct 03 '22 10:10

Matthias


You can explicity define a table for a model using set_table_name or self.table_name depending on your rails version. Also you can define a default scope for every query made for this model, using default_scope, so a combination of both should be what you are searching for:

class Category < AR:Base
  self.table_name = 'boards'
  default_scope where('boards.ancestry IS NOT NULL')
end
like image 24
MurifoX Avatar answered Oct 03 '22 10:10

MurifoX