Rails 3模型将某些列映射到不同的模型属性 [英] Rails 3 model mapping certain columns to different model attributes
问题描述
我有一个名为 DXFTACCTS的旧表,并创建了Rails模型 Account。
I have the old legacy table called "DXFTACCTS", and I created Rails model "Account".
class Account < ActiveRecord::Base
set_table_name "DXFTACCTS"
end
问题是DXFTACCTS具有类似 XORFNAME的字段,我希望在模型中成为 first_name,依此类推。
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?
谢谢!
推荐答案
您可以像这样使用alias_attribute方法:
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创建方法first_name,first_name =和first_name吗?它将映射到表中的XORFNAME列。但是,您将无法在常规列之类的条件下使用它。例如:
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" })
那将会失败...
这篇关于Rails 3模型将某些列映射到不同的模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!