【问题标题】:What is the relationship between these two tables in RoR?RoR中这两个表之间有什么关系?
【发布时间】:2010-07-20 22:44:43
【问题描述】:

我正在开发一个类似 stackoverflow 的应用程序,其中的问题或文章只有一个标签。并且一个标签必须有一篇或多篇文章。

所以,我在 RoR 的迁移中这样做。我正在考虑哪种关系适合这两个表。在文章表中,应该使用“has_many”,在标签表中,应该使用“has_many”。 但我在想是否有必要在中间再添加一张桌子,比如....

所以,第一个是这样的:

class Article < ActiveRecord::Base
  has_many :tags
end

class Tag < ActiveRecord::Base
  has_many :articles
end

或类似的东西:

class Article < ActiveRecord::Base
  has_many :articleTagList
  has_many :tags, :through => : articleTagLists
end

class Tag < ActiveRecord::Base
  has_many :articleTagList
  has_many :articles, :through => :articleTagLists
end

class ArticleTagList < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end

【问题讨论】:

标签: ruby-on-rails migration entity-relationship


【解决方案1】:

规范化数据库中的多对多关系总是需要第三个“查找表”。

如果您进行非规范化,则只需将标签 ID 放在一个字段中并在它们之间使用分隔符即可。但您还必须提供处理检索的逻辑。

我个人会选择标准化选项。

【讨论】:

    【解决方案2】:

    如果您不想在中间表上存储任何信息(例如,将标签 X 添加到问题 Y 的用户的姓名),您可以使用 has_and_belongs_to_many: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

    如果你想存储一些东西,你需要创建中间模型,作为你的例子。在您的示例中,按照惯例,ArticleTagList 模型应称为 ArticlesTag,而数据库表应为articles_tags。

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      相关资源
      最近更新 更多