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

Know if user is blocked

Hi, I have implemented user_friendship model according to the model given in the tutorials.

has_many :blocked_user_friendships, class_name: 'UserFriendship',
                                    foreign_key: :user_id,
                                    conditions: { state: 'blocked_to'}


has_many :blocked_friends, through: :blocked_user_friendships, source: :friend

I can get whole list by current_user.blocked_friends but i want to query about a particular user.

I am right now doing it by

current_user.blocked_friends.include?(user)

I would like to know what will be right way to know if a user is blocked by current_user?

1 Answer

So checking with include? is certainly one way to do it, but if a user has a huge set of blocked_friends it'll certainly slow things down for you. My recommendation would be to implement it by adding a blocked? method on User that looks something like this:

def blocked?(friend)
  blocked_users.where(user_id: friend.id).count > 0
end

That method will basically check if there's a user that matches the friend passed as a parameter, but will check it in the database rather than by pulling the complete set.