hellomello
hellomello

Reputation: 8597

Rails: Record checking if user is already following another user through controller

Is there a quick way of only getting users that have not followed another user yet?

I'm trying to create a little "Suggested users to follow" module and I want to display only users that are nearby and that have not been followed yet.

This is my controller:

@user = User.near(current_user.location,50).where.not(id: current_user.id)

In my view I can get the list of users that are nearby and do some kind of check like this:

- @user.each do |user|
  - if !current_user.following?(user)
    = user.name
    = <follow btn code>

But I want it to already be checked through @user in the controller. I think this would be cleaner, or if someone has any other suggestions?

Upvotes: 0

Views: 119

Answers (1)

Toby 1 Kenobi
Toby 1 Kenobi

Reputation: 5035

It's easy to filter using select of the Enumerable module (already included in ActiveRecord collections)

in the controller:

@user = User.near(current_user.location,50).where.not(id: current_user.id)
@user = @user.select{ |u| !current_user.following?(u) }

but be warned that this will change the type of @user from an ActiveRecord collection to a simple array.

Upvotes: 1

Related Questions