【问题标题】:Rails - Place Condition On Join With IncludesRails - 在加入时放置条件包含
【发布时间】:2012-12-31 03:33:57
【问题描述】:

我正在使用 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])

但我在尝试 debug(@cat_inc) 时收到了 undefined method each for nil:NilClass

我很困惑为什么上面没有产生上面的 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)

【问题讨论】:

  • 您应该立即将您的应用升级到 3.2.11。更新只包含多个极其关键的安全修复程序weblog.rubyonrails.org
  • @Deefour- 谢谢!我知道这个漏洞,但现在这只是一个测试应用程序。不过,我很感激这种担忧。
  • .joins.include 是两个非常不同的东西。您遇到的具体问题是什么?
  • @Deefour - 我实际上是想在:includes 上获得像AND incomes.dept_id = 86 这样的条件连接。我试图在关联上执行此操作,但我得到了一个未定义的方法,如上所述。只是想弄清楚为什么。我是不是看错了。

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


【解决方案1】:

我认为 has_many 应该有复数的 class 词。查看Rails Guide

【讨论】:

  • 感谢 Anand 发现我的错误。不幸的是,修复后仍然会产生相同的错误。
  • 我认为 :include 中不会有任何数组。即它应该像 :include => :income
  • 我认为没有任何可能的方法可以在连接上添加条件,只有在使用includes 连接之后。我已经修复了数组,结果仍然相同。
猜你喜欢
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多