How can I get the class name from an ActiveRecord object?
如何从ActiveRecord对象获取类名?
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.
我知道这是很基本的,但是我搜索了Rails和Ruby的文档,我找不到它。
5 个解决方案
#2
88
Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...
这里给出了正确的答案,摘自Daniel Rikowski和pseidemann的评论。我厌倦了必须通过评论来找到正确的答案……
If you use Rails (ActiveSupport):
如果您使用Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
如果你使用POR(纯-ol- ruby):
result.class.name.split('::').last
#3
31
Both result.class.to_s
and result.class.name
work.
result.class。to_s和result.class.name工作。
#4
1
If you want to get a class name from inside a class method, class.name
or self.class.name
won't work. These will just output Class
, since the class of a class is Class
. Instead, you can just use name
:
如果您想从类方法中获得类名,class.name或self。class.name将不起作用。这些将只输出类,因为类的类是类。相反,您可以使用名称:
module Foo
class Bar
def self.say_name
puts "I'm a #{name}!"
end
end
end
Foo::Bar.say_name
output:
输出:
I'm a Foo::Bar!
#5
0
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
在我的情况下,当我使用result.class. class.name之类的东西时,我得到了一个类似于Module1::class_name的东西。但如果我们只想要class_name,请使用。
result.table_name.singularize
result.table_name.singularize
#1
#2
88
Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...
这里给出了正确的答案,摘自Daniel Rikowski和pseidemann的评论。我厌倦了必须通过评论来找到正确的答案……
If you use Rails (ActiveSupport):
如果您使用Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
如果你使用POR(纯-ol- ruby):
result.class.name.split('::').last
#3
31
Both result.class.to_s
and result.class.name
work.
result.class。to_s和result.class.name工作。
#4
1
If you want to get a class name from inside a class method, class.name
or self.class.name
won't work. These will just output Class
, since the class of a class is Class
. Instead, you can just use name
:
如果您想从类方法中获得类名,class.name或self。class.name将不起作用。这些将只输出类,因为类的类是类。相反,您可以使用名称:
module Foo
class Bar
def self.say_name
puts "I'm a #{name}!"
end
end
end
Foo::Bar.say_name
output:
输出:
I'm a Foo::Bar!
#5
0
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
在我的情况下,当我使用result.class. class.name之类的东西时,我得到了一个类似于Module1::class_name的东西。但如果我们只想要class_name,请使用。
result.table_name.singularize
result.table_name.singularize