djoll
djoll

Reputation: 1229

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!

Upvotes: 0

Views: 760

Answers (1)

Axel Tetzlaff
Axel Tetzlaff

Reputation: 1364

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

Upvotes: 1

Related Questions