Come si ottiene i nomi dei modelli che hanno myObject has_many di?
-
14-11-2019 - |
Domanda
Utilizzo di rubino (1.8.7) e rotaie (2.3.8)
Fare myObject.attributes
ti dà un hash di attributo al valore.
Diciamo che ho lo scenario:
class MyObject
has_many :other_objects
class OtherObject
belongs_to :my_object
.
Dovrebbe esserci un modo per ottenere i nomi delle associazioni legate a un oggetto, giusto?
Anche se non c'è predefinito, sarei interessato all'aiuto con un metodo .Associations, simile al .attributes - tranne, restituire una matrice invece di un hash.
Soluzione
reflect_on_all_associations should do it.
Example:
MyObject.reflect_on_all_associations.map{|a| a.name.to_s} #=> ["other_objects"]
Altri suggerimenti
MyClass.reflections
Gives you all the associations and aggregations that an activerecord has, and gives you all the information you might need about them (class of the associated objects, foreign key etc.)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow