如何通过中介模型进行统计?

时间:2013-03-28 02:28:11

标签: ruby-on-rails ruby-on-rails-3

我正在尝试查找给定帐户的响应数量。

以下是我的协会......

Account has_many :questions
Question belongs_to :account
Question has_many :responses
Responses belongs_to :question

我确信有很多方法可以解决这个问题,所以对于DB调用来说,无论收费最低的是什么......

1 个答案:

答案 0 :(得分:0)

我很确定使用原始sql有更好的方法来实现你想要的东西,但使用ActiveRecord,你应该能够使用以下代码实现你想要的东西

account = Account.first
Response.joins(question: :account).where(accounts: { id: account.id }).count

这将返回第一个帐户的回复数。