Rails 4 has_many:通过包含关联模型的模型

时间:2017-08-24 00:49:18

标签: mysql ruby-on-rails

我有以下型号

class Listing < ActiveRecord::Base
  has_many :agents, through: :listing_agents
end

class Agent < ActiveRecord::Base
  has_many :listings, through: :listing_agents
  has_many :emails
  has_many :phone_numbers
end
class Email < ActiveRecord::Base
  belongs_to :agent
end

class PhoneNumber < ActiveRecord::Base
  belongs_to :agent
end

我想知道什么是最小化运行查询量的最佳方法(给定一组listing_ids),这将返回所有代理,代理列表,代理phone_numbers和代理电子邮件。通常我只需做一些像

这样的事情
Listing.where(id: listing_ids)

如果listing_ids数组变得足够大,那么在获取代理电子邮件,phone_number以及我想要访问的任何其他可能的has_many关联模型时,遇到N + 1查询的主要问题。

这是否可以通过一些聪明的内部联接?也许这会更好地被问为MySQL问题。

0 个答案:

没有答案
相关问题