views:

620

answers:

3

How can I get the class name from an ActiveRecord object?

I have:

result = User.find(1)

I tried:

result.class
# => User(id: integer, name: string ...)
result.to_s
# => #<User:0x3d07cdc>"

I need only the class name, in a string (User in this case). Is there a method for that? I know this is pretty basic, but I searched both rails' and ruby's docs, and I couldn't find it.
Thanks.

+2  A: 

Does result.class.to_s work?

Oliver N.
+16  A: 

You want to call .name on the object's class:

result.class.name
flicken
That is what I was looking for. Thank you.
andi
+3  A: 

Both result.class.to_s and result.class.name works

tal
But conceptually, #name returns the name, #to_s returns a string representation, which just happens to be identical to the name. I'd stick to using #name, just out of anal-retentiveness.
kch