0

正如我已经提到的,我有一个名为Category

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

我需要选择具有特定标题的特定父级的所有子级: Categories Category

Category.where(:category=>{'parents_categories'=>{:title=>'tea'}}) #wrong

它没有按我的需要工作。实际上,它根本不起作用:

Category Load (0.5ms)  SELECT `categories`.* FROM `categories` WHERE `parent`.`title` = 'tea'
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'parent.title' in 'where clause': SELECT `categories`.* FROM `categories`  WHERE `parent`.`title` = 'tea'

我做了一项研究,但一无所获。我该如何解决?

更新:我需要在Category模型中创建一个范围,这将允许我拨打电话:(Category.of_tea确切地说)并将返回属于标题为“ ”的父级的所有类别。 Categorytea

4

1 回答 1

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

  scope: with_title, lambda{|text| where(title: text) }

end

category = Category.find(65) #you know, or whatever
tea_categories = category.children.with_title("tea")
于 2012-09-23T19:13:53.747 回答