通过以下方式在 has_many 上优雅地设置 join table 属性:association

Elegantly set join table attributes on has_many through: association

在我的 Rails 3.2 应用中 Users 可以创建 CollectionsArticlesCollectionsArticleshas_many through: collections_articles 关系连接。

Article 添加到 Collection 时,我希望将 user_id 存储在 collections_articles 连接 table 中。 (这样应用程序可以稍后显示谁将文章添加到集合中)。有没有一种优雅的方法可以做到这一点?

class CollectionsArticle
  collection_id
  article_id
  user_id

  belongs_to :collection
  belongs_to :article
  belongs_to :user

当用户将文章添加到集合中时,我只想使用铲子,所以:

  my_collection.articles << my_article

有没有办法(优雅地)同时将联接 table 的 user_id 设置为 current_user?或者是在连接 table 本身中显式创建记录的最佳方法:

  CollectionsArticle.create(article: @article, collection: @collection, user: current_user)

谢谢!

模型层本身没有current_user的知识,所以你必须以某种方式从控制器层传递它。

我能想到的最优雅的解决方案是在 Collection 模型中创建一个 add_article 方法:

def add_article(article, by_user)
  self.collection_articles.create(article: article, user: by_user)
end

..并从控制器调用它