jeudi 13 août 2015

Elegantly set join table attributes on has_many through: association

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!

Aucun commentaire:

Enregistrer un commentaire