2009-01-26 8 views
5

Esiste un modo per ottenere un elenco dei modelli a cui appartiene un determinato modello in Rails?Accesso alle associazioni in Rails

Ad esempio:

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 

Spero che questo fa un certo tipo di senso!

risposta

6

questo modo si ottiene un hash di oggetti che descrivono le associazioni e altre cose su un dato modello Model.reflections. Vuoi tutti i valori dell'hash che sono classi Reflection::AssociationReflection. Questo codice dovrebbe ottenere l'array desiderato:

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

Esattamente quello che stavo cercando! Grazie molto. –

+0

Risposta stupenda. Spot on. – Tilendor

3

È possibile utilizzare un array per definire le associazioni e utilizzare nelle convalide come:

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

Grazie. Non è il metodo che stavo pensando, ma funziona a meraviglia. –