There are some very useful methods that operate on the names of your models, tables and controllers in Rails. I use them infrequently enough that I have to relearn them every time - so I'm putting them in here:
Given a string with the name of a model (e.g. Project), how can I create an ActiveRecord call on the fly using that model?
str = 'Project'
project = (str.constantize).find(1)
How can I get the name of the corresponding controller ?
controller = str.tableize
Given a string with the name of a controller, how can I get the name of the Class/Model ?
str = 'sales_contact'
model_name = str.camelize
I the string is plural:
str = 'sales_contacts'
model_name = str.classify
How do I do the reverse operation?
str = 'SalesContact'
name = str.underscore
No comments:
Post a Comment