Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.