1
我有屬於類別和等級一個主題模型。軌道4點belongs_to的商店的ID在陣列列
瞭解每個主題屬於最大5-6級和2-3個類別,每個主題的類別ID和級別ID是否可以使用array:true存儲在Postgresql的2列中,或者是不好的做法所以?
我有屬於類別和等級一個主題模型。軌道4點belongs_to的商店的ID在陣列列
瞭解每個主題屬於最大5-6級和2-3個類別,每個主題的類別ID和級別ID是否可以使用array:true存儲在Postgresql的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
聽起來不錯,但是當你請求的主題索引中的作用問題是,如何獲取相關的等級和類別沒有做N + 1個查詢?你必須發出3個不同的查詢(Category.all,Topic.all和Level.all)嗎? –
您可以使用'references'和'includes':它可能看起來像'Topic.where(id:1).includes(:levels).references(:levels)' – yez
要獲取單個Topic,目前還不清楚如何繼續使用Topic索引方法(Topic.all)來顯示類別和級別... –