2017-05-11 123 views
0

我有两个表PromoImage的Rails获得第二条记录连接的表

Promo具有ID和名称

Image已经PROMO_ID名和img_url

assosiations =>宣传片的has_many图像

和我想从image表中获取第二条记录,其中promo_id 1,

for_example如果我这样做Promo.first.images.second这是不好的perfomace 如果我的形象表中有很多记录

所以我想我需要这样的东西Promo.joins(:images).where('????')

回答

0

我想从图像表中提取第二个记录,其中PROMO_ID 1

既然你在images表有promo_id,没有join需要:

Image.where(promo_id: 1).second 
#=> SELECT "images".* FROM "images" WHERE "images"."promo_id" = $1 ORDER BY "images"."id" ASC LIMIT $2 OFFSET $3 [["promo_id", 2], ["LIMIT", 1], ["OFFSET", 1]] 

如果你想也指定图像id,只需将其添加到where

Image.where(promo_id: 1, id: 2) 
#=> SELECT "images".* FROM "images" WHERE "images"."promo_id" = $1 AND "images"."id" = $2 LIMIT $3 [["promo_id", 1], ["id", 2], ["LIMIT", 11]] 

这假定第二图像id2

这两个选项将生成一个简单的查询到您的数据库,所以你不应该有性能问题(我也假设你已经在你的images表中设置索引)。

相关问题