2015-04-02 54 views
1
versions = Version.where({ 
    item_type: 'Product', 
    event: 'update', 
    item_id: account.products.pluck(:id) 
    }) 

我目前的解决方案显示版本变化是查询其中的item_id是一个id数组的papertrail版本。Rails加入多态模型

查询最终看起来像这样...和成长的日常

Version Load (258.6ms) SELECT "versions".* FROM "versions" 
WHERE "versions"."item_type" = $1 AND "versions"."event" = $2 AND 
"versions"."item_id" IN (8526, 8527, 8528, 8529, 35735, 35736, 
35904, 42293, 43000, 46408, 46409, 46410, 46411, 46412, 46413, 
46414, 46415, 46416, 46417, 46418, 46419, 46420, 46421, 46422, 
46423, 46424, 46425, 46426, 46427, 46428, 46429, 46430, 46431, 
46432, 46433, 46434, 46435, 46436, 46437, 4643, .... 
.... 
.... 

有没有更好的方式来做到这一点?

喜欢的东西Version.join('versions.item_id on account.products.ids')

回答

0

猜像

Version.joins('join products on products.id=versions.item_id joins accounts on accounts.id=products.account_id').where(accounts: {id: account.id}, versions: {event: 'update'}) 

可能做的伎俩。但不知道这种方式是否对大型数据库更有效。 Papertrail在item_type,item_id字段上创建复合索引,并在您的选择中使用该索引。在某些情况下加入可能会变慢。

+0

嗯...看来随着我的产品阵列的增长(有可能是成千上万),有一种更有效的方式,就是将一大串ID与其匹配......我真的不知道¯\ _(ツ)_ /¯ – 2015-04-02 22:09:09