Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Kevin Fitzhenry
Kevin Fitzhenry
30,096 Points

Don't print duplicates in Active Record

I am printing out all the users that liked a post in an .html.erb file. A user is allowed to like a post multiple times, but if they did so, I only want to print their name to the page one time.

I have a users table, a posts table and a likes table. The likes table only has a post_id and a user_id.

I feel like there is an easy want to do this in rails perhaps with .include? or something like include_once (if something like that exits)

Thanks in advance for your help.

2 Answers

Seth Reece
Seth Reece
32,867 Points

Hi Kevin,

I don't think there is include_once in Ruby. I would probably create an array by looping through the users in your likes table, then use an if statement to check if the user is not included in the array, push the user to the array. Then iterate through the array in your html.erb file to show the users.

Kevin Fitzhenry
Kevin Fitzhenry
30,096 Points

Thanks, I figured it out. There is an Active Record method called .distinct that will only print the item if it is unique. Exactly what I was looking for.