Rails: includes with polymorphic association
combine 2 objects and sort rails 5
Here is my current code:
user.rb
def photo_feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Photo.approved.where("user_id IN (#{following_ids})", user_id: id)
end
def video_feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Video.approved.where("user_id IN (#{following_ids})", user_id: id)
end
UsersController
def feed
@user_feed_photo_items = current_user.photo_feed.order('created_at desc').paginate(page: params[:page], per_page: 15)
@user_feed_video_items = current_user.video_feed.order('created_at desc').paginate(page: params[:page], per_page: 15)
end
Users follow others users who upload photos and videos. My goal is to stop separating photos and videos and to instead display photos and videos in a polymorphic association as described in the answers above ordered bycreated_at
.
But the above answers that I linked to are much simpler. When a new object is created it is just added to the timeline. In my case, objects will not be added into the timeline until a user follows another user, and when unfollowed they would need to removed form the timeline. And they would still need to be sorted by their created_at
date inside the timeline.
How can I go about achieving this goal?