2015-12-14 40 views

回答

2

請問has_and_belongs_to_many關係對您有用嗎?

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 

這將使結構是這樣的:

|--------|  |--------------| 
| Topics | ---> | LevelsTopics | 
|--------|  |--------------| 
        ^
|--------|   | 
| Levels | ---------| 
|--------| 


|--------|  |-------------------| 
| Topics | ---> | CategoriesTopics | 
|--------|  |-------------------| 
         ^
|------------|   | 
| Categories | ---------| 
|------------| 

這種方式有一個單獨的行,每一個題目,一個單獨的行,從各個層次,一個單獨的行,每個類別。關係邏輯將包含在一個新表中,所以一切都保持乾燥。

瞭解更多關於has_and_belongs_to_many

+0

聽起來不錯,但是當你請求的主題索引中的作用問題是,如何獲取相關的等級和類別沒有做N + 1個查詢?你必須發出3個不同的查詢(Category.all,Topic.all和Level.all)嗎? –

+0

您可以使用'references'和'includes':它可能看起來像'Topic.where(id:1).includes(:levels).references(:levels)' – yez

+0

要獲取單個Topic,目前還不清楚如何繼續使用Topic索引方法(Topic.all)來顯示類別和級別... –