Shauna wrote:
If I were creating a Rails app from scratch I would use Rails's naming conventions for fieldnames (such as first_name). However, I am doing a prototype for a legacy app that has fieldnames like FirstName and for other reasons need to keep them that way. Trust me on that.
The validates_ series works fine with these legacy fieldnames, as do my views and controllers. But when I try to add some methods to my model that manipulate the names, Rails balks. For example, def full_name FirstName + ' ' + (if MI then MI + '. ' else '' end) + LastName end
This is based on an example from Ruby For Rails (p. 84). Rails gives me "NameError in LoansController#list ... uninitialized constant FirstName ... This error occured while loading the following files: first_name.rb".
I tried putting single quotes around 'FirstName' (that turned it into a literal), using it as a symbol :FirstName, and putting brackets around it. I know the syntax itself is okay because if I substitute created_on.to_s for FirstName then that part is properly rendered by the view.
I understand that Rails is supposed to favor convention but allow you to deviate if you must. So how do I refer to my nonstandard fieldnames within model methods?
You can use either self.FirstName or self[:FirstName].
Or you can create a set of facade accessor methods, perhaps in a loop, using the underscore method to de-camelize every field name.