使用 Rails 3.2。我的模型是这样嵌套的:
- 审核 => 可审核(国家或商店)
- 国家 => CountryDay => 商店 => 照片
- 商店 => 照片
我有以下内容:
@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 根据其关联包含正确的模型?
我想我刚才也遇到了同样的问题。我得到了一个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()
-仅获取您需要的声明。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)