DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Dan has posted 4 posts at DZone. View Full User Profile

Model From Table Name

11.20.2006
| 9589 views |
  • submit to reddit
        Get the Rails model based on the table name.  Assumes standard table name conventions.

def model_for_table(table_name)
  table_name.classify.constantize
end
    

Comments

Snippets Manager replied on Fri, 2006/06/02 - 8:45pm

Er, not 'versatile', but 'verbose'.

Snippets Manager replied on Fri, 2006/06/02 - 8:45pm

I posted a more versatile version of this a while back, as well as the opposite method for turning a model into a string akin to the table name. See http://www.bigbold.com/snippets/posts/show/2135

Snippets Manager replied on Tue, 2006/08/15 - 7:37pm

Maybe this one is easier to read (and to understand): def model_for_table(table_name) table_name.to_s.classify.constantize end

Dan Manges replied on Mon, 2006/11/20 - 2:26am

Looking into it, classify returns a string, but the singularize is unnecessary. I'll update the snippet.

Snippets Manager replied on Mon, 2012/05/07 - 2:32pm

I'm pretty sure that classify actually returns the constant (not just the string name of the constant), so you shouldn't need the eval.