渴望加载不同的嵌套多态

编程入门 行业动态 更新时间:2024-10-26 18:17:36
本文介绍了渴望加载不同的嵌套多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用 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.

更多推荐

渴望加载不同的嵌套多态

本文发布于:2023-08-04 06:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   加载   多态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!