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

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

def model_for_table(table_name)


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

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

Snippets Manager replied on Fri, 2006/06/02 - 7: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

Snippets Manager replied on Tue, 2006/08/15 - 6: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 - 1: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 - 1: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.