"Category", :foreign_key => "parent_i..." />

无法加入自连接表中的RailsRails

2023-09-09 22:01:23 作者:只做独一无二的自己

我有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

在特定的,类别有标题为茶父项目,这个项目有很多孩子的项目:红茶,白茶......

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

由于未知parent.id列。

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

我甚至尝试

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

和它并没有帮助

请,你的看法。

推荐答案

连接的操作()这里是pretty的聪明,在其中()部分是不高明。 AFAIK它不知道任何有关的连接和真的只是它的参数转换为字符串。因此,试试这个:

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})

为了避免流血内部使用的AR到code中的名称,请考虑使用AREL您的查询。已经有关于这个问题的一些优秀的railscasts最近。

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.