Search code examples
ruby-on-railsactiverecordscopes

How to make chainable methods (scopes) with conditions not tied to database


I have a model Item, which has a relation to itself.

class Item < ActiveRecord::Base
  has_many :subitems, :class_name => "Item", :foreign_key => "superitem_id"
  belongs_to :superitem, :class_name => "Item"
end

And I want to query all items which have a parent. Firstly I've tried to check if parent_id is present Item.where("superitem_id != ?", false), or something like this. But it doesn't work. Although that item has superitem_id, superitem can be already destroyed. So I have to do it with class method

def self.with_superitems
  items = []
  self.find_each do |i|
    items << i if i.superitem
  end
  return items
end

But it makes chaining impossible, and I want to chain it with similar methods, like

def self.can_be_stored
  items = []
  self.find_each do |i|
    items << i if i.can_be_stored?
  end
  return items
end

Is it possible to achieve the same results with scopes? Or what would you do?


Solution

  • I've had a similar issue in the past. It's sometimes difficult to get round it. I found a hack-ish way of doing it for my purposes so hope this will help...

     ids = []
     self.find_each do |i|
        ids << i.id if i.superitem
     end
    Model.where('id in (?)', ids)