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开发者_StackOverflow社区 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!
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...
I think something like definition of getter and setter methods should do the trick:
class Account < ActiveRecord::Base
...
def firts_name
self[:XORFNAME]
end
def first_name= value
self[:XORFNAME] = value
end
...
end
精彩评论