[英]Elegantly set join table attributes on has_many through: association
In my Rails 3.2 app Users
can create Collections
of Articles
. 在我的Rails 3.2应用程序中, Users
可以创建Articles
Collections
。 Collections
and Articles
are joined by a has_many through: collections_articles
relationship. Collections
和Articles
是由加入has_many through: collections_articles
关系。
I wish to store the user_id
in the collections_articles
join table when an Article
is added to a Collection
. 当将Article
添加到Collection
时,我希望将user_id
存储在collections_articles
连接表中。 (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
Is there anyway to (elegantly) simultaneously set user_id
of the join table to current_user
? 无论如何,要(优雅地)同时将user_id
表的user_id
设置为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)
Thanks! 谢谢!
The model layer itself does not have knwoledge of the current_user
, so you have to pass it in from the controller layer somehow. 模型层本身不具有current_user
,因此您必须以某种方式从控制器层传递它。
The most elegant solution I can come up with is to create an add_article
-method in the Collection
model: 我能想到的最优雅的解决方案是在Collection
模型中创建一个add_article
方法:
def add_article(article, by_user)
self.collection_articles.create(article: article, user: by_user)
end
..and call that from the controller ..然后从控制器中调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.