Would a has_and_belongs_to_many relationship work for you?
class Topic
has_and_belongs_to_many :levels
has_and_belongs_to_many :categories
end
class Category
has_and_belongs_to_many :topics
end
class Level
has_and_belongs_to_many :topics
end
create_table :categories_topics do |t|
t.integer :topic_id
t.integer :category_id
end
create_table :levels_topics do |t|
t.integer :level_id
t.integer :topic_id
end
This would make the structure look like:
|--------| |--------------|
| Topics | ---> | LevelsTopics |
|--------| |--------------|
^
|--------| |
| Levels | ---------|
|--------|
|--------| |-------------------|
| Topics | ---> | CategoriesTopics |
|--------| |-------------------|
^
|------------| |
| Categories | ---------|
|------------|
This way there is a single row for each Topic, a single row for each Level and a single row for each Category. The relationship logic will be contained in a new table so everything stays DRY.
Read more about has_and_belongs_to_many