渴望加载不同的嵌套多态 [英] Eager load differently nested polymorphic
问题描述
使用 Rails 3.2.我的模型是这样嵌套的:
Using Rails 3.2. My models are nested in such a way:
- 评论 => 可评论(国家或商店)
- 国家 => CountryDay => 商店 => 照片
- 商店 => 照片
我有以下几点:
@reviews = @user.reviews.includes(:user, :reviewable)
通常我们可以通过以下方式包含嵌套多态:
Usually we can include nested polymorphic in such a way:
# 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 包含基于其关联的正确模型?
There are many other variants. How do I work around it to have the ActiveRecord includes the correct model based on its association?
推荐答案
我想我刚才也遇到了同样的问题.尝试加载关联时出现 ActiveRecord::EagerLoadPolymorphicError
.我的解决方案是将自定义连接语句放在一起,我已将其放入一个范围内以便于使用.
I think I had the same problem just now. I got an ActiveRecord::EagerLoadPolymorphicError
when trying to load associations. My solution was to put together a custom join statement which I've put into a scope for easier usage.
未经测试,但这可能会让您前进:
Untested, but this may get you going:
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()
语句以仅获取您需要的语句.
You then use @user.reviews.eagerly_loaded
. Make sure to use a matching .group()
-statement to only get the ones you need.
这篇关于渴望加载不同的嵌套多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!