【问题标题】:Rails: apply where conditions to both model and associationsRails:将 where 条件应用于模型和关联
【发布时间】:2013-04-02 21:46:11
【问题描述】:

在我的应用程序中,我有如上定义的模型 Item、Category 和 Categorization:

    class Item < ActiveRecord::Base
      attr_accessible :name, :description, :property_valuations, :barcode

      has_many :categorizations
      has_many :categories, :through => :categorizations
    end

    class Category < ActiveRecord::Base
      attr_accessible :name, :description, :parent, :children, :items, :parent_id

      has_many :children, :class_name => "Category", :foreign_key => "parent_id", :dependent => :nullify
      belongs_to :parent, :class_name => "Category"

      has_many :categorizations
      has_many :items, :through => :categorizations

      def all_children(children_array = [])
        children = Category.where(:parent_id => self.id).includes(:items)

        children_array += children.all
        children.each do |child|      
          children_array = child.all_children(children_array)
        end
        children_array
      end

    end

class Categorization < ActiveRecord::Base
  attr_accessible :category, :item

  belongs_to :category
  belongs_to :item

end

我正在递归搜索类别树以查找与类别关联的项目。但是,除了按 parent_id 过滤类别之外,我还想应用过滤器项目名称。我该怎么做(我期待像 Category.where(:parent_id =&gt; self.id).includes(:items).where(:name =&gt; 'something...') 这样的东西)?

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby associations where


    【解决方案1】:

    你可以的

    Category.where(:parent_id => self.id).includes(:items).where("items.name like ?", '%cheap%')
    

    这将获得类别,以及符合条件的项目。

    即:

    categories = Category.where(:parent_id => 2).includes(:items).where("items.name like ?", 'AA%')
    categories.first.items.size # -> 2
    categories.first.id # -> 1
    Category.find(1).items.size # -> 3
    Category.find(1).items.where("name like ?", 'AA%').count # -> 2
    

    如果只想获取父类的子类的项:

    parent_category = Category.find(2)
    Item.joins(:categories).where(categories: {parent_id: parent_category.id}).where("items.name like ?", 'AA%')
    

    【讨论】:

    • 这不是只获取与所选类别的直接子类别相关联的项目吗?
    • 获取与您要查找的项目关联的类别,当您检查每个类别的项目时,它只获取与条件匹配的项目。你想得到什么结果?这个问题不清楚(至少对我来说)。
    • 假设您想检查 all_children 中的所有 id,如果您创建一个数组 all_children_ids,那么您可以找到(all_children_ids),这将导致高效的“Find xx in”sql 而不是重复查询如果您单独点击 id。
    • 他为他的模型写了代码和他遇到的问题,如果你有更好的方式查询当天,为什么不写一个不同的答案建议的代码?他解释说他想得到所有的物品,而不仅仅是 id。
    • 他还明确想要与所选顶级类别的所有后代类别相关联的项目。通过从 find(one_id) 更改为 find(all_ids_array) 来处理您的答案似乎是一个很小的编辑,假装它是另一个答案是愚蠢的。
    【解决方案2】:

    您的数据库可能支持递归查询(以避免您的 all_children 函数的手动递归),例如 postgres 通过 with 命令,但 rails 没有访问它的包装器。如果这种递归经常发生,可能值得在这里阅读一下:http://gmarik.info/blog/2012/10/14/recursive-data-structures-with-rails——看起来确实有一些有前途的宝石可以解决这个问题,但我个人没有使用过它们中的任何一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      相关资源
      最近更新 更多