Rails 3 model mapping certain columns to different model attributes

久未见 提交于 2019-12-23 21:38:47

问题


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  


来源:https://stackoverflow.com/questions/5073823/rails-3-model-mapping-certain-columns-to-different-model-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!