Rails:包含多态关联 [英] Rails: includes with polymorphic association

查看:82
本文介绍了Rails:包含多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关使用多态性制作广告的有趣文章更好地在Rails中提供活动.

我们最终得到类似的东西

We end up with something like

class Activity < ActiveRecord::Base
  belongs_to :subject, polymorphic: true
end

现在,例如,如果其中两个主题为:

Now, if two of those subjects are for example:

class Event < ActiveRecord::Base
  has_many :guests
  after_create :create_activities
  has_one :activity, as: :subject, dependent: :destroy 
end

class Image < ActiveRecord::Base
  has_many :tags
  after_create :create_activities
  has_one :activity, as: :subject, dependent: :destroy 
end

将create_activities定义为

With create_activities defined as

def create_activities
  Activity.create(subject: self)
end

并且客人和标签定义为:

And with guests and tags defined as:

class Guest < ActiveRecord::Base
  belongs_to :event
end

class Tag < ActiveRecord::Base
  belongs_to :image
end

如果我们查询记录的最近20个活动,则可以执行以下操作:

If we query the last 20 activities logged, we can do:

Activity.order(created_at: :desc).limit(20)

我们有第一个N + 1查询问题,可以解决:

We have a first N+1 query issue that we can solve with:

Activity.includes(:subject).order(created_at: :desc).limit(20)

但是,当我们呼叫访客或标签时,我们又遇到了N + 1个查询问题.

But then, when we call guests or tags, we have another N+1 query problem.

为了能够使用分页功能,什么是解决该问题的正确方法?

推荐答案

希望这将在rails 5.0中修复.已经存在一个问题,并且对此有请求请求.

This will hopefully be fixed in rails 5.0. There is already an issue and a pull request for it.

https://github.com/rails/rails/pull/17479

https://github.com/rails/rails/issues/8005

我已经分叉了护栏并将补丁应用到4.2稳定的版本,并且对我有用.即使我不能保证定期与上游同步,也可以随时使用我的fork.

I have forked rails and applied the patch to 4.2-stable and it works for me. Feel free to use my fork, even though I cannot guarantee to sync with upstream on a regular basis.

https://github.com/ttosch/rails/tree/4-2-stable

这篇关于Rails:包含多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆