Forum: Ruby on Rails Getting model class by string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Gitte W. (Guest)
on 2006-01-06 19:36
(Received via mailing list)
Hello,

I have an interessting problem, I'm not sure how to solve :-)
I have the name of a model in a variable like this:
My model is called Article
My var contains "Article"

Now - How do I get the model class, so I can call Article.find,
Article.new etc ... ?

Greetings,
Gitte W.
Rick O. (Guest)
on 2006-01-06 19:57
(Received via mailing list)
On 1/6/06, Gitte W. <removed_email_address@domain.invalid> wrote:
> Greetings,
> Gitte W.

'Article'.constantize

--
rick
http://techno-weenie.net
Jakob L. Skjerning (Guest)
on 2006-01-06 20:03
(Received via mailing list)
Gitte W. wrote:
> I have an interessting problem, I'm not sure how to solve :-)
> I have the name of a model in a variable like this:
> My model is called Article
> My var contains "Article"
>
> Now - How do I get the model class, so I can call Article.find,
> Article.new etc ... ?

eval("Article").find and eval("Article").new. I believe there's at least
one other way, but it eludes me at the moment.

Do realize though, that this poses a big security hole if you pass
tainted data to eval. eval("Article.destroy_all && Article") is fairly
boring to run for example.
Gitte W. (Guest)
on 2006-01-07 02:07
(Received via mailing list)
Jakob L. Skjerning wrote:
>
> eval("Article").find and eval("Article").new. I believe there's at least
> one other way, but it eludes me at the moment.
>
> Do realize though, that this poses a big security hole if you pass
> tainted data to eval. eval("Article.destroy_all && Article") is fairly
> boring to run for example.
>

I'm aware of the security issues. But I won't call .destroy or anything
- and the classes are taking from a db and evaluated before. It's just
for some lookup methods in my model.

Thank you very much for the help.

Greetings,
Gitte W.
This topic is locked and can not be replied to.