使用Rails 3.2。我的模型以这样的方式嵌套:
我有以下内容:
@reviews = @user.reviews.includes(:user, :reviewable)
通常我们可以用这样的方式包含嵌套的多态:
# this will return errors because :shop is not found in the model Shop (:reviewable is actually :shop)
@reviews = @user.reviews.includes(:user, :reviewable => [:shop])
# this will return errors because :photos is not directly associated to Country
@reviews = @user.reviews.includes(:user, :reviewable => :photos)
还有许多其他变种。我如何解决它让ActiveRecord根据其关联包含正确的模型?
答案 0 :(得分:1)
我想我刚才遇到了同样的问题。尝试加载关联时我得到ActiveRecord::EagerLoadPolymorphicError
。我的解决方案是整合一个自定义连接语句,我已将其放入范围以便于使用。
未经测试,但这可能会让你前进:
class Review < ActiveRecord::Base
scope :eagerly_loaded, -> {
joins('
INNER JOIN shops
ON (reviews.reviewable_type = "Shop" AND reviews.reviewable_id = shops.id)
INNER JOIN countries
ON (reviews.reviewable_type = "Country" reviews.reviewable_id = countries.id)
')
}
end
然后使用@user.reviews.eagerly_loaded
。请务必使用匹配的.group()
语句来获取您需要的语句。