kidcapital
kidcapital

Reputation: 5174

Get type of rails model?

If I have a user model.

sample_user = User.all.first

Is there a way in Ruby to get type back in a String? Something like:

typeof(sample_user) == "User"

Upvotes: 5

Views: 3927

Answers (3)

Substantial
Substantial

Reputation: 6682

If you are doing comparison, use #kind_of? or #is_a?

sample_user = User.first

sample_user.kind_of? User
#=> true

sample_user.is_a? User
#=> true

Upvotes: 3

Nitin
Nitin

Reputation: 7366

You can do it multiple ways :

1st :

sample_user.is_a? User

2nd :

sample_user.class.to_s == "User"

and more :). But if you want to check class type with object. Then 1st One would be good.

Upvotes: 6

Raj
Raj

Reputation: 22926

sample_user.class.name 

will give you "User"

Upvotes: 6

Related Questions