问题
I have 2 models
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
In particular, Category has a parent item titled "tea" and this item has many children items: "black tea", "white tea"...
I need to select products that belong to a parent category "tea". Here is how I'm doing that:
Product.joins(:category=>:parent).where(:category=>{:parent=>{:id=>1}}).all
It throws an exception (unable to format it well)
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
because of unknown parent.id column.
Obviously, the query should be (it's working perfect):
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
I even tried
Product.joins(:category=>:parent).where(:category.parent=>{:id=>1}).all
and it didn't help
Please, your thoughts.
回答1:
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.
来源:https://stackoverflow.com/questions/12554579/unable-to-join-self-joins-tables-in-rails