ruby on rails - When building an index of items, how to show which a user has liked/starred -


in rails 4/5, i'm trying show list of items, , if searching user has liked or saved of these items, display somewhere on index. similar social networks showing feed of posts , allowing me see whether i've liked post, or showing list of items , marking whether i've saved of items on list.

for simple example, imagine have user, post, , likedpost join model. users can create posts, , other users can posts. user, can through posts , see if i've liked 1 of posts.

in theory, should work:

@posts = post.includes(:liked_posts)              .where('liked_posts.user_id = ?', current_user.id)              .references(:liked_posts) 

but performs query only shows me posts i've liked. other posts filtered out.

i'm having strangely hard time finding relevant online, , able find comes down 'you'll need write sql.' tips/advice?

ok, on index page have list of posts right? , each post... display name or something? why not have like:

<%= image_tag 'heart.png' if post.liked_by?(current_user) %> 

on page next name in post model like

 def liked_by?(user)     self.liked_posts.where(:user_id => user.id).exists?  end 

(note: not checked typos , minor bugs)


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -