通过以下方式在has_many上优雅地设置联接表属性: [英] Elegantly set join table attributes on has_many through: association

查看:77
本文介绍了通过以下方式在has_many上优雅地设置联接表属性:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails 3.2应用程序中,用户可以创建文章收藏集 $ c>。 馆藏文章 has_many通过以下方式加入:collections_articles

In my Rails 3.2 app Users can create Collections of Articles. Collections and Articles are joined by a has_many through: collections_articles relationship.

我希望将 user_id 存储在 collections_articles 商品添加到 Collection 时,c>连接表。 (因此,该应用程序可以稍后显示谁将文章添加到集合中)。

I wish to store the user_id in the collections_articles join table when an Article is added to a Collection. (So the app can later show who added an article to a collection). Is there an elegant way to do this?

class CollectionsArticle
  collection_id
  article_id
  user_id

  belongs_to :collection
  belongs_to :article
  belongs_to :user

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

When a user adds an article to a collection I'd just like to use the shovel, so:

  my_collection.articles << my_article

是否存在(优雅地)同时设置 user_id current_user ?或者最好是在联接表本身中显式创建记录的最佳方法:

Is there anyway to (elegantly) simultaneously set user_id of the join table to current_user? Or is the best way just to explicitly create the record in the join table itself:

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

谢谢!

推荐答案

模型层本身没有 current_user 的知识,因此您必须从控制器中将其传递

The model layer itself does not have knwoledge of the current_user, so you have to pass it in from the controller layer somehow.

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

The most elegant solution I can come up with is to create an add_article-method in the Collection model:

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

。并从控制器中调用它

这篇关于通过以下方式在has_many上优雅地设置联接表属性:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆