问题
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