0

我正在使用 Rails 3.2.9 并尝试将表的所有结果返回到由联接上的 department_id 过滤的categories表的任何匹配结果。incomesSQL 查询相当简单:

SELECT * FROM categories LEFT OUTER JOIN incomes ON incomes.category_id = categories.id AND dept_id = 86

现在我已经能够通过以下方式达到预期的结果joins

Category.joins('LEFT OUTER JOIN incomes ON incomes.category_id = categories.id AND incomes.dept_id = 86')

但我不知道为什么我不能让它与include. 以下是我的模型:

类别

class Category < ActiveRecord::Base
  attr_accessible :cat_code, :cat_ds
  has_many :incomes, :conditions => ['dept_id = ?', 86]                   
end

收入

class Income < ActiveRecord::Base
  attr_accessible :category_id, :year_id,:dept_id, :note
  belongs_to :category
end

我尝试了许多不同的方法来获得所需的结果,但我将用上述模型说明我最近的尝试。

@cat_inc = Category.find(:all, :include => [:incomes])

但是我undefined method each for nil:NilClass在尝试debug(@cat_inc)

我很困惑为什么上面没有产生上面的 SQL 语句。有任何想法吗?

编辑 也许是一种更好的表达方式,我怎样才能有条件加入?就像上面的 SQL 语句有:AND dept_id = 86

我能得到的最接近的是:

Category.includes(:incomes).where("incomes.dept_id = ?", 86)

这给了我 LEFT OUTER JOIN 但在AND dept_id = 86加入后执行条件。

SELECT "categories"."id" AS t0_r0, "categories"."cat_code" AS t0_r1, "categories"."cat_ds" AS t0_r2, "incomes"."id" AS t1_r0, "incomes"."category_id" AS t1_r1, "incomes"."year_id" AS t1_r2, "incomes"."chart_id" AS t1_r3, "incomes"."dept_id" AS t1_r4, "incomes"."note" AS t1_r5, "incomes"."jan" AS t1_r6, "incomes"."feb" AS t1_r7, "incomes"."created_at" AS t1_r8, "incomes"."updated_at" AS t1_r9 FROM "categories" LEFT OUTER JOIN "incomes" ON "incomes"."category_id" = "categories"."id" WHERE (incomes.dept_id = 86)
4

1 回答 1

0

我认为 has_many 应该有复数的类词。查看Rails 指南

于 2013-01-16T18:25:51.567 回答