RAILS: How to get has_many associations of a model

后端 未结 3 409
猫巷女王i
猫巷女王i 2020-12-10 01:46

how I can get the has_many associations of a model?

For example if I have this class:

class A < ActiveRecord::Base
  has_many B
  has_many C
end
<         


        
相关标签:
3条回答
  • 2020-12-10 02:08

    You should be using ActiveRecord reflections.

    Then you can type something like this:

    A.reflect_on_all_associations.map { |assoc| assoc.name}
    

    which will return your array

    [:B, :C]
    
    0 讨论(0)
  • 2020-12-10 02:13

    Found the solutions:

    def self.get_macros(macro)
      res = Array.new
      self.reflections.each do |k,v|
        res << k if v.macro == macro.to_sym
      end
      return res
    end
    
    0 讨论(0)
  • 2020-12-10 02:14

    For Example you could try :

    aux=Array.new
    Page.reflections.each { |key, value| aux << key if value.instance_of?(ActiveRecord::Reflection::AssociationReflection) }
    

    Hi Pioz , Have a Nice Day!

    0 讨论(0)
提交回复
热议问题