1

I want to perform a query that selects all users that are "allowed" to interact according to the following method:

User.rb

def allowed?(other_user)
  self.friends.include?(other.user) || self.followers.include?(other_user)
end

The problem is that .select { |user| ... } is returning an array, not a collection. How should I write the query correctly so further database queries can be appended (such as limit or order)?

users controller

@user = current_user

@users = User.select { |user| @user.allowed?(user) }
             .limit(100)
             .order(created_at: :desc)
             .paginate(page: params[:page])

1 Answer 1

2

The allowed? method can be written as a class method as:

def self.allowed(other_user)
  User
    .joins(:friends, :followers)
    .where(
      'friends.user_id = :user_id OR followers.user_id = :user_id',
      user_id: other_user.id
    )
end

Which uses joins to specify the relationships of both friends and followers tables with users.

That makes allowed easily chainable, so you can have your allowed? method as a predicate in case you need it:

def self.allowed?(other_user)
  User.allowed(other_user).exists?
end

So you can do:

User
  .allowed(@user)
  .limit(100)
  .order(created_at: :desc)
  .paginate(page: params[:page])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.