Reputation: 250
I have a database of users which is related by a has_many relationship to a articles database.
I would like a user to be able to have a list of favorite articles, for which he is not the author. I'm not sure how to implement this. I initially thought of an array for the user which holds all the id's of the posts which he favorited, but there seems like a more intuitive way to do it.
Upvotes: 0
Views: 188
Reputation: 1963
Probably you'd like the favorites to live in the database as well as the author relationship. The way to do this is to add another join table, perhaps called "favorite_articles".
create_table :favorite_articles, :id => false do |t|
t.integer :user_id
t.integer :article_id
end
# also add foreign keys, assuming you're using a database that supports them
Then add a model for it which :belongs to both users and articles and use the has_many :through association in both users and articles. You will have to name the association something other than articles, though.
class User < ActiveRecord::Base
has_many :favorite_articles
has_many :favorites, :through => :favorite_articles, :class_name => "Article"
end
class FavoriteArticle < ActiveRecord::Base
belongs_to :user
belongs_to :article
end
class Article < ActiveRecord::Base
has_many :favorite_articles
has_many :users_who_favorited, :through => :favorite_articles, :class_name => "User"
end
Upvotes: 1