Querying multiple related records in Rails
I would try to use as much as possible what is provided by ActiveRecord. I was thinking to something like:

class Account &lt; ActiveRecord::Base
  belongs_to :accountable, touch: true, polymorphic: true
  CLAUSE_FOR_RELATED = '"accounts"."accountable_type" = \'%s\' AND "accounts"."accountable_id" IN (%s)'.freeze

  class &lt;&lt; self
    def related_to_user(user)
      group_ids = user.groups.pluck('groups.id')
      friend_ids = user.following_friendships.pluck('friendships.following_id') 

      query = [
        compose_clause('Group', group_ids.join(', ')),
        compose_clause('User', [user.id, *friend_ids].join(', '))
      ].join(' or ')

      where(query)
    end

    def related_to_group(group)
      member_ids = group.members.pluck('users.id')
      where(compose_clause('User', member_ids.join(', ')))
    end

    private
    def compose_clause(accountable_type, ids)
      sprintf(CLAUSE_FOR_RELATED, accountable_type, ids)
    end
  end
end


Now in Rails 5 you could even write it like:

class Account &lt; ActiveRecord::Base
  belongs_to :accountable, touch: true, polymorphic: true

  class &lt;&lt; self
    def related_to_user(user)
      group_ids = user.groups.pluck('groups.id')
      friend_ids = user.following_friendships.pluck('friendships.following_id') 

      where(accountable_type: 'Group', accountable_id: group_ids).or(
         Account.where(accountable_type: 'User', accountable_id: [user.id, *friend_ids])
      )
    end

    def related_to_group(group)
      member_ids = group.members.pluck('users.id')
      where(accountable_type: 'User', accountable_id: member_ids)
    end
  end
end