1

Suppose I have a DataMapper scope for carnivores, like this:

class Animal
  #...
  def self.carnivores
    all(:diet => 'meat')
  end
  #...
end

Can I reuse that scope in an association's scope?

class Zoo
  #...
  def self.with_carnivores
    # Use `Animal.carnivores` scope to get zoos that have some?
    all(:animals => ???)
  end
  #...
end
Nathan Long
  • 122,748
  • 97
  • 336
  • 451

1 Answers1

1

You can do this by going "in reverse" from the association.

 class Zoo
  #...
  def self.with_carnivores
    # Assuming `Animal belongs_to :zoo`
    Animal.carnivores.zoo
  end
  #...
end

class Habitat
  #...
  def self.with_carnivores
    # Assuming `Animal has_many :habitats`
    Animal.carnivores.habitats
  end
  #...
end
Nathan Long
  • 122,748
  • 97
  • 336
  • 451