2012-05-17 140 views
1

假設我有一個食肉動物DataMapper的範圍,就像這樣:DataMapper作用域是否可以使用關聯模型的作用域?

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

我可以重複使用範圍在關聯的範圍是什麼?

class Zoo 
    #... 
    def self.with_carnivores 
    # Use `Animal.carnivores` scope to get zoos that have some? 
    all(:animals => ???) 
    end 
    #... 
end 

回答

1

您可以通過從協會「反向」進行此操作。

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 
相關問題