2009-01-26 10 views
5

Existe-t-il un moyen d'obtenir une liste des modèles auxquels appartient un modèle particulier dans Rails?Accès aux associations dans Rails

Par exemple:

class Project < ActiveRecord::Base 
    has_one :status 
    ... 
end 

class Task < ActiveRecord::Base 
    has_one :status 
    ... 
end 

class Status < ActiveRecord::Base 
    belongs_to :project 
    belongs_to :task 

    # this is where I want to be able to pass in an array of the associations' class 
    # names (to be used for checking input) rather than having to do w%{ project task } 
    # which leaves it open to failure if I add new associations in future 
    validates_inclusion_of :status_of, :in => ? 
    ... 
end 

Hope this fait une sorte de sens!

Répondre

6

Cela vous obtenir un hachage d'objets décrivant les associations et autres sur un modèle donné Model.reflections. Vous voulez toutes les valeurs dans le hachage qui sont Reflection::AssociationReflection classes. Ce code devrait vous obtenir le tableau que vous voulez:

association_names = [] 
Model.reflections.each { |key, value| association_names << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) } 
+0

Exactement ce que je cherchais! Merci beaucoup. –

+0

Super réponse. Spot sur. – Tilendor

3

Vous pouvez utiliser un tableau pour définir les associations et l'utilisation dans les validations comme:

BELONGS_TO_LIST = w%{ project task } 
BELONGS_TO_LIST.each {|b| belongs_to b} 
validates_inclusion_of :status_of, :in => BELONGS_TO_LIST 
+0

Merci. Pas la méthode à laquelle je pensais mais ça marche. –