结果失去了has_many关联的条件

时间:2014-09-26 08:31:35

标签: ruby-on-rails ruby-on-rails-4

目标

我有一个projectproject有很多activity项与之关联。 对于下一个功能,我想选择一个Project给定activities,但只选择activities个给定日期范围内的Invoice

模型

  
    

我已经包含了Invoice模型,因为我还希望在代码的下一次迭代中包含class Project < ActiveRecord::Base has_many :activities has_many :invoices end class Activity < ActiveRecord::Base belongs_to :project belongs_to :invoice end class Invoice < ActiveRecord::Base belongs_to :project end 个实例。

  
project

获取@project

这是按id加载给定@project = Project.includes(:activities).where( activities: { done_at: params[:from]..params[:to] } ).references(:activities).friendly.find( params[:id] ) 的方式:

SELECT "projects"."id" AS t0_r0, "projects"."title" AS t0_r1, "projects"."description" AS t0_r2, "projects"."created_at" AS t0_r3, "projects"."updated_at" AS t0_r4, "projects"."slug" AS t0_r5, "activities"."id" AS t1_r0, "activities"."title" AS t1_r1, "activities"."body" AS t1_r2, "activities"."hours" AS t1_r3, "activities"."done_at" AS t1_r4, "activities"."project_id" AS t1_r5, "activities"."created_at" AS t1_r6, "activities"."updated_at" AS t1_r7, "activities"."invoice_id" AS t1_r8, "activities"."service" AS t1_r9 FROM "projects" LEFT OUTER JOIN "activities" ON "activities"."project_id" = "projects"."id" WHERE ("activities"."done_at" BETWEEN '2014-08-01' AND '2014-08-31') AND "projects"."slug" = 'my-website' AND "projects"."id" IN (1)  ORDER BY "projects"."id" ASC

生成的SQL如下所示:

Project

生成的#<Project id: 1, title: "My Website", description: "HTML Templates for their new website", created_at: "2014-09-24 07:35:39", updated_at: "2014-09-25 07:10:19", slug: "my-website"> 实例如下所示:

@project

问题

当我对结果activities进行迭代时,我看到所有与其相关的activities。不属于给定日期范围内的那些。因此,除了预期的41个相关activities之外,我看到所有200 + {{1}}。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

事实证明应该使用size来计算集合中的项目数。如果您使用count Rails将再次访问数据库。 * 面团 *