【问题标题】:User authors many articles, also has a list of favorite articles Rails用户作者多篇文章,也有收藏Rails文章列表
【发布时间】:2013-07-20 09:56:59
【问题描述】:

我有一个用户数据库,它通过 has_many 关系与文章数据库相关。

我希望用户能够拥有他不是作者的最喜欢文章的列表。我不确定如何实现这一点。我最初为用户考虑了一个数组,其中包含他最喜欢的帖子的所有 id,但似乎有一种更直观的方式来做到这一点。

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

您可能希望收藏夹和作者关系一样保存在数据库中。这样做的方法是添加另一个连接表,可能称为“favorite_articles”。

create_table :favorite_articles, :id => false do |t|
  t.integer :user_id
  t.integer :article_id
end

# also add foreign keys, assuming you're using a database that supports them

然后为其添加一个模型:属于用户和文章,并在用户和文章中使用has_many :through 关联。不过,您必须为关联命名而不是文章。

class User < ActiveRecord::Base
  has_many :favorite_articles
  has_many :favorites, :through => :favorite_articles, :class_name => "Article"
end

class FavoriteArticle < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end

class Article < ActiveRecord::Base
  has_many :favorite_articles
  has_many :users_who_favorited, :through => :favorite_articles, :class_name => "User"
end

【讨论】:

  • 这是明智的做法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多