【问题标题】:Self joins in Ruby on RailsRuby on Rails 中的自联接
【发布时间】:2012-09-23 18:56:33
【问题描述】:

因为我已经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

我需要选择所有 child Categories 具有特定 parent 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(确切地说)并将返回所有属于 父级children 类别/strong> Category,标题为“tea”。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord join


    【解决方案1】:

    为您的类别添加一个范围,然后在您的父对象上使用它:

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

    【讨论】:

    • 这不是我需要的。 Scope 是一种正确的方法,但是这个category.children.with_title("tea") 看起来很丑。我想要这样的东西:Category.of_tea
    • 类似Category.of_tea.with_parent(@parent)?
    • 不。正是Category.of_tea
    • 毫无疑问,您绝对需要指定您想要孩子的类别。没有办法解决这个问题。
    • 不,你不想要of_tea。您想要 of_tea 解决您提出的不同问题
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多