【问题标题】:How to correctly maintain database schema in rails?如何正确维护 Rails 中的数据库模式?
【发布时间】:2018-05-02 21:00:19
【问题描述】:

我有这样的架构:

create_table "grades", force: :cascade do |t|
    t.integer "cls"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "post_grades", force: :cascade do |t|
    t.integer "post_id"
    t.integer "grade_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.integer "user_id", null: false
    t.string "title"
    t.text "content"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

create_table "user_grades", force: :cascade do |t|
    t.integer "user_id"
    t.integer "grade_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

在这个架构中,等级、帖子和用户都是相互关联的。

所以我的第一个问题:这样做是否正确?

假设一个用户在他的列中添加了等级 4 (cls = 4),而另一个用户添加了相同的等级。现在我在成绩表中对于两个不同的成绩 id 有相同的 cls 值。那么这个架构中是否有任何数据冗余?

【问题讨论】:

  • 你能描述一下你的表的逻辑吗?没有任何概念性的理解就很难说有用的东西
  • 用户有多个等级,可以在这些等级发布帖子。年级可以有很多职位,一个职位只能在一个年级。一个等级可以有许多用户。是否足够或需要详细说明?
  • Grade 是否有任何特定用户,例如创作者/等,或者他们都相似?
  • 什么是cls?是的,您的回复让事情变得有点清楚,但仍需要更多信息来帮助您
  • 是的,这个用户有很多角色,比如管理员、教师和学生,其中只有管理员和教师可以在成绩中发布帖子。

标签: ruby-on-rails ruby-on-rails-5 database-schema table-relationships


【解决方案1】:

当我得到你的任务时,你可以采用这样的解决方案:

  1. grades -> 没有引用(现在是这样)
  2. user_grades(命名此表的传统方式是grades_users...按字母顺序排列,并且都是复数形式)-> user_id、grade_id(就像现在一样)
  3. 你不需要post_grades。这是多余的
  4. posts -> grade_id, user_id(如果需要作者)

你的schema.rb 看起来像:

create_table "users", force: :cascade do |t|
  ...
end

create_table "grades_users", force: :cascade do |t|
  t.integer "user_id"
  t.integer "grade_id"
  ...
end

create_table "grades", force: :cascade do |t|
  ...
end

create_table "posts", force: :cascade do |t|
  t.integer "user_id", null: false
  t.integer "grade_id", null: false
  ...
end

【讨论】:

  • 假设一个用户在他的列中添加了等级(cls:4),而另一个用户添加了相同的等级。现在我在成绩表中对于两个不同的成绩 id 有相同的 cls 值。所以这也是数据冗余吗?
  • 不,这不是数据冗余,因为按照这种方法,您最终可能会发现所有重复数据都是冗余的。您是否需要仅使用唯一的 cls 字段创建 Grade?
  • No..for a specific User ..Grade 仅使用唯一的 cls 字段创建,但当然不同的用户可以拥有与其他用户相同的 cls 字段..
  • 然后一切正常。并且,请让我们回到您最初的问题。现在这已经是一个新问题了。我的回答对你有帮助吗?如果是,那么请用打勾标记它并为将来的搜索投票。提前失去了感谢。
猜你喜欢
  • 2014-08-10
  • 2013-05-03
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
相关资源
最近更新 更多