I would like to give users of my application the opportunity to remove from their microposts' feed unwanted microposts. By default the microposts' feed is made of the user's own microposts plus the microposts from followed users:
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
I created a Quarantine
model where users and unwanted microposts are associated. Then I looked for an ActiveRecord::Relation
method that allowed me to subtract from the above where
the following where
:
microposts_ids = "SELECT micropost_id FROM quarantines
WHERE user_id = :user_id"
Micropost.where("micropost_id IN (#{microposts_ids})", user_id: id)
I could not find any method that correspond to the -
arrays operator. However I found method merge
in a Stackoverflow question: Combine two ActiveRecord::Relation objects, that, as far as I understood, would allow me to chain the wheres
as follows:
Micropost.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id).merge(Micropost.where.not("micropost_id IN (#{microposts_ids})", user_id: id))
The difference is that I changed the second where
into a where.not
.
The problem with this solution is that the where.not
would load all Microposts that are not quarantined, which is a heavier job for the database than loading only the quarantined microposts. Is there any alternative solution to the merge
method, such as a method that subtracts from the original feed the quarantined microposts?