Rails - 加入包含的放置条件

时间:2013-01-16 18:02:31

标签: ruby-on-rails join rails-activerecord

我正在使用Rails 3.2.9并尝试将categories表的所有结果返回到incomes表的任何匹配结果,该结果由连接上的department_id过滤。 SQL查询非常简单:

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)

1 个答案:

答案 0 :(得分:0)

我认为has_many应该有多元化的课程。查看Rails Guide