自我加入Ruby on Rails

时间:2012-09-23 18:56:34

标签: ruby-on-rails ruby activerecord join

我已经mentioned,我有一个名为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(确切地说)并返回属于<的所有类别标题为“Category”的强>父 tea

1 个答案:

答案 0 :(得分: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")