我有 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
它没有帮助
请,你的想法。