Rails 3 model mapping certain columns to different

2019-07-15 12:22发布

问题:

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!

回答1:

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...



回答2:

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