1

My rails application is wired up to a legacy database and there's a column with a space in it. I created an alias_attribute and that lets me access said field, but if I try to access a field that's defined afterwards, I get a syntax error. How do I tell rails to only use the alias_attribute and ignore the field with a space?

class Atg < ActiveRecord::Base
 alias_attribute :modified_ts, :'Modified TS'
end

=> #<Atg primary_shot: nil, product_id: "1000000007", category_number: nil, vm_ready: nil, Modified TS: "2014-02-28 07:31:40", size_code: "NS1003715">

error I'm getting if I try to retrieve the size_code:

/home/action/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/attribute_methods/time_zone_conversion.rb:36: formal argument cannot be a constant def Modified TS=(time)
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Scott Hillson
  • 900
  • 1
  • 12
  • 30

2 Answers2

0

There may be a better way, but here is a gem I'd recommend looking at that looks like it deals with your exact issue:

https://github.com/bjones/safe_attributes

It deals with legacy databases and weird column names. Let me know if this works for you. If nothing else, you may be able to see what they did in the gem code and apply it to your situation.

Mike Riley

Mike Riley
  • 282
  • 3
  • 20
  • That doesn't seem to be doing the trick, and Rails 4 seems to have rendered that gem obsolete. – Scott Hillson May 21 '14 at 22:31
  • I think the issue that you are coming up against is that alias_attribute only defines a new method but will still call the old one. In other words even though you have modified_ts it is still calling "Modified TS" The alias attribute is just another way to call the same column. I found this. It seems to be a hack, but it may work: http://stackoverflow.com/questions/5147814/is-there-a-way-to-rename-activerecord-model-columns. This is an interesting issue. Hope I can help you figure it out. – Mike Riley May 22 '14 at 03:10
0

I highly recommend to migrate the column name to a valid Rails column name. If that is impossible for some reasons, There might be the option to set a DB view on top of that table with valid attribute names, if your database supports persistable views. The rename-columns-hack mentioned in a comment would be definitely the least solution. For a better understanding, how Module#alias_attribute works, I recommend reading Aliasing the Rails way.

Community
  • 1
  • 1
Christian Rolle
  • 1,664
  • 12
  • 13