Search code examples
sqlrubyruby-on-rails-3activerecordlegacy

Rails 3 model mapping certain columns to different model attributes


I have the old legacy table called "DXFTACCTS", and I created Rails model "Account".

class Account < ActiveRecord::Base
  set_table_name "DXFTACCTS"
end

The problem is that DXFTACCTS has fields like "XORFNAME" which I want to be "first_name" in the model, and so on. How do I "map" specific table columns to model attributes?

Thanks!


Solution

  • You can use the method alias_attribute like this:

    class Account < ActiveRecord::Base
      set_table_name "DXFTACCTS"
    
      alias_attribute :first_name, :XORFNAME
    end
    

    alias_attribute creates the methods first_name, first_name= and first_name? which will map to the XORFNAME column in your table. However, you will NOT be able to use it in conditions like regular columns. For example:

    Account.all(:conditions => { :first_name => "Foo" })
    

    That will fail...