Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically find parent object from belongs_to

An example schema is "book belongs_to library"

r = Book.reflect_on_all_associations(:belongs_to).first

The above would give the first reflection. I can then do "r.name" to get "library" (well, assuming no other belongs_to).

So my question is... If I wanted to dynamically access the "Library" class, how would I do that?

I don't want to manually use "Library.all" (etc), since I'm trying to make it a generic thing.

My initial attempt is something like this:

r.name.singularize.classify.constantize

But that seems awkward.... is there a more proper way?

like image 604
Dolbery Avatar asked Jan 30 '26 12:01

Dolbery


1 Answers

I just tried this in my console:

k = Post.reflect_on_all_associations(:belongs_to).first.active_record
# => User
k.first
# => returns the first user
like image 164
MrYoshiji Avatar answered Feb 02 '26 06:02

MrYoshiji