【问题标题】:Rails model associations [closed]Rails 模型协会[关闭]
【发布时间】:2017-11-08 22:43:52
【问题描述】:

我在构思一个在我的 Rails 应用程序中创建两个不同模型之间关联的好方法时遇到了麻烦。

目前我有一个 Person 模型和一个 Note 模型。一个人可以是笔记的作者或主题。因此:

  • 一个可以属于许多笔记(作为主语)。
  • 一个可以有很多注释(作为作者)。
  • 注释属于一位作者(person)。
  • note 可以有一个主题(person)。

我想该应用需要显示Person个人资料,我们可以在其中看到Person撰写的所有Notes /em>,以及所有关于PersonNotes

设置此模型关联的最佳方式是什么?直接,还是通过中间关系模型?

提前致谢!

【问题讨论】:

标签: ruby-on-rails ruby model-associations


【解决方案1】:

在我看来,最简洁的方法是让笔记属于作者和主题:

class Note < ActiveRecord::base
  belongs_to :author, class_name: 'Person', foreign_key: :author_id
  belongs_to :subject, class_name: 'Person', foreign_key: :subject_id
end

class Person < ActiveRecord::base
  has_many :authored_notes, class_name: 'Note', foreign_key: :author_id
  has_many :notes_about_me, class_name: 'Note', foreign_key: :subject_id
end

您可能想更改上述关系的名称,但您明白了。

我知道我们通常不会认为有关某人的便条属于该便条的主题。然而,从 Rails 的角度来看,belongs_to 关系允许我们将subject_id 外键放在notes 表上,这是最简单的解决方案。如果您要使用has_one 关系,则必须创建一个连接表,在我看来,这会增加不必要的复杂性。

确保您的notes 表有两个对persons 表的索引引用,称为subject_idauthor_id。您可以通过这样的迁移来做到这一点:

class AddSubjectAndAuthorToNotes < ActiveRecord::Migration
  def change
    add_reference :notes, :author, index: true
    add_reference :notes, :subject, index: true

    add_foreign_key :notes, :people, column: :author_id
    add_foreign_key :notes, :people, column: :subject_id
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多