views:

48

answers:

3
m = Model.find(1);

m.class_name would give you "Model"

If we have:

m = Model.find(:all);

How do we get the name of the model from m alone?

+3  A: 

Get the class of the first entry in the returned array

m.first.class
Farrel
This won't work quite correctly if you've got inheritence. Given, say, `Media < ActiveRecord::Base`, `Record < Media`, and `ComicBook < Media`, `Media.find(:all)` will return some things that are `Record`s and some that are `ComicBook`s.
James A. Rosen
+1  A: 

If you mean, how do you aggregate them all, since you are actually returning an array of Model objects, I recommend this:

Model.find(:all).collect(&:model_name)

This should give you an array of model names of the classes that you have returned from the database.

Derek P.
+1  A: 

If you are calling "Model", don't you already know the class?

If you call

Post.find(:all)

the returned records will be of class Post.

Toby Hede
This is not always true. If you are dealing with an STI model, and you are querying the parent/base model, it can return subclasses of this that are known as different model names.
Derek P.