2009-11-27 3 views
1

Je pense que quelque chose comme ceci:obtenir une liste des objets avec des rôles appliqués dans be9 acl9

def self.obj_list(opts = {:include => [] , :exclude => []}) 
    # Returns an array with all objects with roles applied 
    # +:exclude+:: (array,string) optional object type to exclude from list 
    # +:include+:: (array,string) optional object type to include in list 
    # Example: 
    # Role.obj_list(:include => ["Device", "User"]) 
    # Role.obj_list(:exclude => ["User"]) 

    inc = opts[:include].to_a 
    exc = opts[:exclude].to_a 

    objs = [] 
    if inc.empty? 

     self.all.each do |r| 
     unless r.authorizable_type.nil? 
      objs << r.authorizable_type.constantize.find(r.authorizable_id) unless exc.include?(r.authorizable_type) 
     end 
     end 

    else 

     self.all.each do |r| 
     unless r.authorizable_type.nil? 
      objs << r.authorizable_type.constantize.find(r.authorizable_id) if inc.include?(r.authorizable_type) 
     end 
     end 

    end 
    objs 
    end 

Répondre

0

Vous pouvez utiliser where clauses faire l'inclure/exclure des choses dans SQL:

(inc.empty? 
? where.not(:authorizable_type => exc) 
: where(:authorizable_type => inc) 
).map(&:authorizable) 

En utilisant authorizable vous obtiendrez propre traitement des Rails polymorphes associations, qui garantira que seuls les objets réels sont retournés, il n'est donc pas nécessaire de vérifier nil

Questions connexes