Is there a way to list all belongs_to associations?

后端 未结 3 458
悲哀的现实
悲哀的现实 2020-12-13 06:21

I need to list all belongs_to associations in a model object and iterate through them. Is there a way to do this?

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 06:44

    Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact 
    #=> ["Foo", "Bar"]
    

    of course, you can pass :has_many, or any other associations too

提交回复
热议问题