Tampa Bay won its fifth straight and claimed its 17th victory this month, the franchise's most ever in July.
The Rays overcame a two-run deficit in the third -- Longoria scoring the tying run on a fielder's choice grounder from Willy Aybar. Jason Bartlett put Tampa Bay in front for good with an RBI single in the fourth.
Longoria hit his 15th home run in the eighth inning, a two-run shot that boosted what had been a one-run lead.
Jeff Niemann (9-3) got the win by battling through six innings. He gave up four runs on eight hits and walked two. Rafael Soriano worked a perfect ninth for his 28th save.
Eddie Bonine (4-1) made his first start of the season and suffered the loss. He allowed five runs on eight hits over 3 1/3 innings.
Detroit has dropped five out of six.