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

Snippets has posted 5883 posts at DZone. View Full User Profile

Go From Model To Associated Table Name And Back

06.02.2006
| 8574 views |
  • submit to reddit
        Given a table object, it returns the related string object; e.g. SubAttribute => 'sub-attribute'.  Useful if you want to make a list of all your tables with perhaps their fields listed out to the side.

def stringify_table( table, replace_char = '-', pluralize = false )
  string = table.to_s.gsub( /([A-Za-z])([A-Z])/, '\1' << replace_char.to_s << '\2' )
  string = string.pluralize if pluralize
  string
end

Given a string akin to the name of a table, it returns the related table object; e.g. 'sub_attributes' => SubAttribute.

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join )
end
    

Comments

Snippets Manager replied on Mon, 2007/11/26 - 1:42pm

There are Rails helpers for these functions: classify and tableize. No need to write your own!

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

That's generally where I put them, yes. It just depends on the scope of where you need them, however. If you're only going to use them in, say, FuzzyController, then put them there. I put them in ApplicationController because I use them in various places throughout my other controllers. If you need them in both helpers and controllers, it's best to put them in app/helpers/application_helper.rb and then use this tutorial to make them accessible inside controllers.

Snippets Manager replied on Mon, 2006/08/28 - 1:11pm

Where is the best place to add these methods? app/controllers/application.rb?