The pull request with all the code.

This whole block is not immediately obvious what it does.  Perhaps extract this block out into a private method that takes params as an argument. Then name that method with an obvious name for what you are doing.  That way, your code is a bit easier to grok at first sight for someone else who might be working with you.  Plus I feel if you properly name you methods(being descriptive while still relatively concise) you can do away with comments.  Again this is a stylistic thing, but it honestly makes code a bit easier to read.  Perhaps a method named `find_friends`.  I also think perhaps could be a class method on `User`.  There is a lot of logic going on in the controller, which should perhaps be placed in a model or another object(perhaps a service object if you are interacting between multiple other models.