Never been to DZone Snippets before?

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

Model from Table Name (See related posts)

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 on this post

tsaleh posts on Nov 20, 2006 at 01:59
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.
dcmanges posts on Nov 20, 2006 at 02:14
Looking into it, classify returns a string, but the singularize is unnecessary. I'll update the snippet.
NoKarma posts on Nov 20, 2006 at 12:37
Maybe this one is easier to read (and to understand):

def model_for_table(table_name)
table_name.to_s.classify.constantize
end
moneypenny posts on Nov 20, 2006 at 15:22
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
moneypenny posts on Nov 20, 2006 at 15:24
Er, not 'versatile', but 'verbose'.

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts