2016-09-20 61 views
2

我有一个存储类的名称的变量里面我的课让Rails的识别字符串

my_class = "Homework" 

这个类有一定的属性,我想访问

Homework.find_by 

我怎样才能让红宝石看到这个字符串作为一个对象?

例如

my_class.find_by 

回答

3

您可以使用classifyconstantize

my_class.classify.constantize.find_by # something 

classify

Create a class name from a plural table name like Rails does for table names to models. Note that this returns a string and not a Class (To convert to an actual class follow classify with constantize).

constantize

Tries to find a constant with the name specified in the argument string.

'Module'.constantize  # => Module 
'Test::Unit'.constantize # => Test::Unit 

如果你确定你的输入,你只需要constantize

my_class.constantize.find_by # something 
+0

'2.3.1:015 >'模块'.constantize NoMethodError:未定义方法'constantize'为“Module”:String' – Bula

+2

您需要导轨控制台,而不是irb。 –