无法在Rails中加入自联接表

我有2个型号

class Category  "Category" has_many :children, :class_name => "Category", :foreign_key => "parent_id" has_many :products attr_accessible :description, :title, :parent end class Product < ActiveRecord::Base belongs_to :category end 

特别是,类别有一个标题为“茶”的父项,这个项目有很多儿童项目:“红茶”,“白茶”……

我需要选择属于类“茶”的产品。 我是这样做的:

 Product.joins(:category=>:parent).where(:category=>{:parent=>{:id=>1}}).all 

它抛出exception(无法格式化)

 Product Load (0.8ms) SELECT `products`.* FROM `products` INNER JOIN `categories` ON `categories`.`id` = `products`.`category_id` INNER JOIN `categories` `parents_categories` ON `parents_categories`.`id` = `categories`.`parent_id` WHERE `parent`.`id` = 1 ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'parent.id' in 'where clause': SELECT `products`.* FROM `products` INNER JOIN `categories` ON `categories`.`id` = `products`.`category_id` INNER JOIN `categories` `parents_categories` ON `parents_categories`.`id` = `categories`.`parent_id` WHERE `parent`.`id` = 1 

因为未知的parent.id列。

显然,查询应该是(它的工作完美):

  SELECT `products`.* FROM `products` INNER JOIN `categories` ON `categories`.`id` = `products`.`category_id` INNER JOIN `categories` as `parents_categories` ON `parents_categories`.`id` = `categories`.`parent_id` WHERE `parents_categories`.`id` = 1 

我甚至试过了

 Product.joins(:category=>:parent).where(:category.parent=>{:id=>1}).all 

它没有帮助

拜托,你的想法。

虽然这里的joins()操作非常聪明,但where()部分并不那么聪明。 AFAIK它对连接一无所知,只是将其参数转换为字符串。 因此,试试这个:

 Product.joins(:category=>:parent).where(:parents_categories=>{:id=>1}) 

为了避免AR内部使用的名称出现在代码中,请考虑使用AREL进行查询。 最近有关于该主题的一些优秀的轨道广播。