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.
Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.
What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.
You want to call .name on the object's class:
result.class.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With