简体   繁体   English

Rails模型:一个可以属于但有很多吗?

[英]Rails Models: Can one belong and yet have many?

Say I have two tables in a database: a user and and an article. 假设我在数据库中有两个表:一个用户和一个文章。 A user creates the article, but the article can also be saved to a different user's list (these are just examples, don't ask me why they'd do that). 用户可以创建文章,但也可以将文章保存到其他用户的列表中(这些只是示例,不要问我为什么要这么做)。 How would this relationship be represented in a database since a set has a one-to-one created with relationship with a user, but at the same time it could also have many users if they added it to their items? 由于集合是通过与用户的关系一对一创建的,因此该关系将如何在数据库中表示,但是同时如果将其添加到项目中,它也可能会有许多用户? Is something like the following possible (I am writing this in Rails)? 是否可能出现以下情况(我正在用Rails编写)?

class User

  #something

end

class Article

  belongs_to :user
  has_many :users

end

Or would you need to add an additional list Table? 还是需要添加其他列表表?

class User

  has_many :lists
  has_many :articles, through: :lists

end

class Article

  has_many :lists
  has_many :users, through: :lists

end

class List

  belongs_to :user
  belongs_to :article

end

The second approach is indeed how you would do it. 第二种方法确实是您将如何做。 You could, in addition, have a separate belongs_to :user relationship from Article to User to indicate authorship, as you had in the first approach. 此外,您可以像在第一种方法中那样,从ArticleUser具有单独的belongs_to :user关系以指示作者身份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM