簡體   English   中英

無法在Rails中聯接自聯接表

[英]Unable to join self-joins tables in Rails

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

特別是,類別具有一個名為“茶”的父項目,而該項目有許多子項目:“紅茶”,“白茶” ...

我需要選擇屬於類別“茶”的產品。 這是我的做法:

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

它沒有幫助

拜托,你的想法。

盡管這里的joins()操作非常聰明,但是where()部分並不那么聰明。 AFAIK它對連接一無所知,實際上只是將其參數轉換為字符串。 因此,請嘗試以下操作:

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

為了避免將AR內部使用的名稱泄露給您的代碼,請考慮對查詢使用AREL。 最近有一些關於該主題的精彩報道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM