0
表我有2種型號無法加入自連接在Rails的
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
特別是,類別有標題爲「茶」父項目,這個項目有很多孩子的項目:「紅茶」,「白茶「......
我需要選擇屬於父母類別」茶「的產品。這裏是我正在做的是:
Product.joins(:category=>:parent).where(:category=>{:parent=>{:id=>1}}).all
它拋出,因爲未知parent.id列的例外(無法很好地格式化)
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
。
顯然,查詢應(它的工作完美):
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
,並沒有幫助
請,您的想法。