0

我有 2 个模型

class Category < ActiveRecord::Base
  belongs_to :parent, :class_name => "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

特别是,Category 有一个名为“tea”的父项,该项有许多子项:“红茶”、“白茶”......

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

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

它抛出一个异常(无法很好地格式化它)

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

它没有帮助

请,你的想法。

4

1 回答 1

0

While the operation of joins() here is pretty smart, the where() part isn't so clever. AFAIK it doesn't know anything about the joins and really just converts its arguments to strings. As such, try this:

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

In order to avoid bleeding the name used internally by AR to your code, consider using AREL for your query. There have been some excellent railscasts on that subject recently.

于 2012-09-23T17:54:18.147 回答