# Type casting

**URL:** <https://www.ruby-forum.com/t/type-casting/96694>\
**Category:** Rails\
**Created:** [June 30, 2006, 9:44pm UTC](https://www.ruby-forum.com/t/type-casting/96694 "2006-06-30T21:44:32Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![barry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/958977/32.png) [@barry](https://www.ruby-forum.com/u/barry)\
**Post date:** [June 30, 2006, 9:44pm UTC](https://www.ruby-forum.com/t/type-casting/96694/1 "2006-06-30T21:44:32Z")

</div>

Hello,  
I have a user table linked to the login code that was in the  
“Agile” book. When someone signs in they are assigned to a group, such  
as “adult” or “teenager”. I would like to take this group string and  
reference a table with “find\_by\_sql()” so that:  
(group.capitalize).find\_by\_sql() would work (and, of course, in the  
select request in the parameter I would concatenate an “s” for the table  
name: (select name from " + group + “s”) ).  
An error is produced that the string “Adult” does not have a method  
“find\_by\_sql”, so the code has not type cast the string to the model.  
How do I call that model?  
Thanks,  
Barry

---

<div class="post-metadata">

**Author:** ![barry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/958977/32.png) [@barry](https://www.ruby-forum.com/u/barry)\
**Post date:** [July 1, 2006, 1:33am UTC](https://www.ruby-forum.com/t/type-casting/96694/2 "2006-07-01T01:33:09Z")

</div>

barry wrote:

> How do I call that model?  
> Thanks,  
> Barry

group.capitalize.constantize.find\_by\_sql() should work, as should any of  
the normal AR find methods, e.g.  
group.capitalize.constantize.find(:all), etc

---

<div class="post-metadata">

**Author:** ![barry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/958977/32.png) [@barry](https://www.ruby-forum.com/u/barry)\
**Post date:** [July 3, 2006, 5:59pm UTC](https://www.ruby-forum.com/t/type-casting/96694/3 "2006-07-03T17:59:11Z")

</div>

Thanks, Chris!  
“constantize” worked. I didn’t know that command existed. It  
allowed me to generalize the code so that future tables won’t require a  
code change. Thanks, again!  
Barry

Chris T wrote:

> barry wrote:
> 
> > How do I call that model?  
> > Thanks,  
> > Barry
> 
> group.capitalize.constantize.find\_by\_sql() should work, as should any of  
> the normal AR find methods, e.g.  
> group.capitalize.constantize.find(:all), etc

---

<div class="post-metadata">

**Author:** ![barry](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/958977/32.png) [@barry](https://www.ruby-forum.com/u/barry)\
**Post date:** [July 3, 2006, 7:24pm UTC](https://www.ruby-forum.com/t/type-casting/96694/4 "2006-07-03T19:24:19Z")

</div>

It’s not well documented (Saw Ezra mention it in a post a while back),  
and there are other ways of doing it, but I like its conciseness, and  
have used it in quite a few places.
