与同一模型具有两个关系时的 Rail命名约定



我的问题与命名约定有关,而不是我猜的编程。

让我们假设一个应用程序,用户可以在其中创建新文章(因此他们是这些文章的所有者),并且可以在其中添加文章"编辑器",他们只能更新文章内容。

class User
  include Mongoid::Document
  has_many :articles # as owner of the articles
  has_and_belongs_to_many :articles # as editor of the articles
end
class Article
  include Mongoid::Document
  belongs_to :user
  has_and_belongs_to_many :editors, :class_name => 'User'
end

我想知道的是我应该如何在我的用户模型中调用文章关联。我的意思是,一篇文章有作者和编辑,这对我来说似乎是很强的命名约定,但用户有他创建的文章和他是编辑的文章。您将如何调用/命名/声明最后两个关联?

我会称它们为:edited_articles:authored_articles:owned_articles,或类似简单的名字。只是不要忘记添加:class_name:foreign_key:through限定符。

更新:

对于has_and_belongs_to_many关系,您需要一个连接表,默认情况下,该表由两个连接表命名。 例如 articles_users在你的情况下。在此表中,您可能有两个 ID,user_idarticle_id 。这样,轨道会自动连接您的模型。

has_and_belongs_to_many :editors, :class_name => 'User', :foreign_id => 'user_id'

当然,如果您在连接表中editor_id调用它,请使用它。相反,在用户端也应该有效。

最新更新