我想我的问题更多地与命名约定有关,而不是编程。
让我们假设一个应用程序,其中用户可以创建新文章(因此他们是这些文章的所有者),您可以在其中添加只能更新文章内容的文章“编辑”。
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我想知道的是,我应该如何在我的用户模型中调用文章关联。我的意思是,一篇文章有作者和编辑,这对我来说似乎是很强的命名约定,但用户有他自己创建的文章和他是编辑的文章。如何调用/name/声明最后两个关联?
发布于 2012-04-25 20:40:49
我会称它们为:edited_articles、:authored_articles或:owned_articles,或者其他类似的简单名称。但不要忘记向它们添加:class_name和:foreign_key或:through限定符。
更新:
对于has_and_belongs_to_many关系,您需要一个连接表,默认情况下,该连接表由两个连接表命名。例如,在你的情况下是articles_users。在此表中,您可能有两个ids:user_id和article_id。这样,rails会自动连接您的模型。
has_and_belongs_to_many :editors, :class_name => 'User', :foreign_id => 'user_id'当然,如果您在连接表中将其称为editor_id,那么就使用它。相反,在用户端也应该起作用。
https://stackoverflow.com/questions/10315688
复制相似问题