Creating multiple relationships in rails with same datatypes
-
23-09-2019 - |
Question
What I am trying to do is kind of like this:
I have datatypes "user" and "article" for instance. I want to have relationships between these two, but in more than one way.
So for instance, I'd like to let a user "like" or "bookmark" an article. So I need to have two relations in the database, one for users liking the article, and one for users bookmarking, so making a "user_article" table for instance won't be sufficient, correct?
What is the best way of going about doing this?
Solution
What you are describing are "Data Models" not "Data Types". Data types = String, integer etc. If it is a Active Record Object it's a Data Model or a Active Record Model more specifically.
Eimantas pointed out you are describing a 2 "has_many" relationships but not "have_many" as written in his post. In his example the bookmarkings is called a join model. Remember you can place other things in the join model and use the relationships there to accomplish things. Say you want to have a bookmark order or a favorite rank- the join model is the idea spot for this.
Stripped down example:
class Article < ActiveRecord::Base
has_many :users, :through => :user_bookmarks
end
class UserBookmark < ActiveRecord::Base
belongs_to :user
belongs_to :article
end
class User < ActiveRecord::Base
has_many :user_bookmarks
has_many :articles, :through => :user_bookmarks
end
Things to look at after getting the basics down: Counter caches - if you are doing counts they are your friend.
It is likely way easier and cleaner to just use these 2 join models rather than try to dive into polymorphism right now. After you get that up and running you could explore that next.
OTHER TIPS
I'd suggest Bookmarking
model that have bookmarking_type
(note that type
is reserved for RoR). Then you could has_many :bookmarkings
and has_many :liked_articles, :through => :bookmarkings
and has_many :bookmarks, :through => :bookmarkings
. Of course you should add conditions or just join SQL to these assocations, but all should be good. I do believe there's even plugin for that, just can't recall the name atm.