Elegantly set join table attributes on has_many through: association

泪湿孤枕 提交于 2019-12-11 19:44:29

问题


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.

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

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)

Thanks!


回答1:


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

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

..and call that from the controller



来源:https://stackoverflow.com/questions/31982343/elegantly-set-join-table-attributes-on-has-many-through-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!