The ruling dealt a setback to the Trump administration’s plans for hundreds of miles of barriers that have drawn local opposition.