1

我是 Ruby on Rails 的新手。现在我正在研究 Rails 应用程序的性能问题。我正在使用 New Relic rpm 来找出代码的瓶颈。在这样做时,我发现了一些我无法弄清楚的东西。问题是,在我的 Rails 应用程序中,我使用了两个模型 A、B 和 C,其中模型 B 有两个属性:A 的主键和 C 的主键,如下所示:

class B
  include DataMapper::Resource
  belongs_to :A, :key=>true
  belongs_to :C, :key=>true
end

A的模型如下:

 class A
   include DataMapper::Resource
   property :prop1
   ...
   has n, :bs
   has n, :cs, :through => :bs
 end

在发出以下语句 a.find(:c.id=>10) 时,它在内部执行以下 SQL 查询:

 select a.prop1, a.prop2,... from a INNER JOIN b on a.id = b.a_id INNER JOIN c on b.c_id = c.id where (c.id=10) GROUP BY a.prop1, a.prop2,....[here in group by all the properties that has been mentioned in select appears, I don't know why]

并且此语句在网络交易期间花费了太多时间。有趣的是,当我在终端的 mysql 提示符中执行相同的自动生成查询时,所花费的时间非常少。我认为这是因为在 group by 子句中提到了这么多字段。我无法理解查询是如何形成的。如果有人能帮我解决这个问题并优化它,我将不胜感激。谢谢你。

4

1 回答 1

0

我假设您已经正确配置了模型关联,如下所示:

class A < ActiveRecord
  has_many :B
  has_many :C, through: :B
end

class B < ActiveRecord
  belongs_to :A
  belongs_to :C
end

class C < ActiveRecord
  has_many :B
  has_many :A, through: :B
end

那么你可以简单地调用:

a.c.find(10) #mind the plural forms though

通过这种方式,您将获得更好的性能。

于 2013-09-05T02:55:29.550 回答