Rails 4 belongs_to在数组列中存储id

时间:2015-12-14 22:13:15

标签: ruby-on-rails postgresql belongs-to

我的主题模型属于类别级别

知道每个主题属于最多5-6级和2-3个类别,每个主题的类别ID和级别ID是否可以使用数组存储在2列中:对于Postgresql是真的,或者这样做是不好的做法?

1 个答案:

答案 0 :(得分: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