RAILS: How to get has_many associations of a model

南笙酒味 提交于 2019-12-17 19:13:13

问题


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

I would a method like this:

A.get_has_many

that return

[B,C]

Is it possible? Thanks!


回答1:


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]



回答2:


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!




回答3:


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


来源:https://stackoverflow.com/questions/2880591/rails-how-to-get-has-many-associations-of-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!