在模型中交叉引用时,rails包括has_many

时间:2018-11-01 11:35:45

标签: ruby-on-rails activerecord ruby-on-rails-5 has-many-through

class Foo
  # attribute amount
  has_many :foobars
  has_many :bars, through: :foobars
end

class Bar
  has_one :foobars
  has_one :foo, through: :foobar

  # this method gets automatically included in the bar object as attribute
  def amount
    self.foo.amount
  end
end

class FooBar
  belongs_to :foo
  belongs_to :bar
end

class FoosController
  def show
     foo = base_class.find(some_id)
     respond_with foo.as_json(include: :bar)
  end

  def base_class
    Foo.includes(:foobars, :bars)
  end
end

重要的部分是controller#base_class,其中包含了一些关系,以减少由于:bar包含在:foo响应中而对数据库造成的压力。但是我遇到了一个n + 1问题,因为:bar也加载了foo.amount项目符号gem建议在:foo上加上Foo.includes(:foobars, :bars),但是foo没有foo关系,并且显然会失败

如何包含/预加载/加入以解决n + 1个问题?

0 个答案:

没有答案