gpt4 book ai didi

ruby-on-rails - 让 Rails 在字符串中识别我的类

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:42 25 4
gpt4 key购买 nike

我有一个存储类名的变量

my_class = "Homework"

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

Homework.find_by

如何让 ruby​​ 将此字符串视为对象?

例如

my_class.find_by

最佳答案

您可以使用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

关于ruby-on-rails - 让 Rails 在字符串中识别我的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39604292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com