无法在Rails中加入自联接表
我有2个型号
class Category "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
它抛出exception(无法格式化)
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进行查询。 最近有关于该主题的一些优秀的轨道广播。
- ActiveRecord where.not不工作/奇怪的行为
- 如何构建用于查询Redshift数据库的前端(希望使用Rails)
- Rails没有保存更改的属性
- 升级到Rails 3.2.2:如何解决与Delayed Job gem相关的’未定义的Syck :: DomainType方法’错误?
- SyntaxError:(irb):26:既给出块arg又给出实际块
- Rails 3 – 如何从具有订单的模型中获取行号
- Rails accepted_nested_attributes_for始终创建嵌套模型,但不更新它们
- Rails“ActiveRecord_Associations_CollectionProxy的未定义方法”
- 如何在新的has_many关联上使ActiveRecord bump updated_at