处理具有非 Rails 常规命名的遗留系统。请注意,所有表和属性都是大写的,这在 sqlserver-adapter 中表示ID
与id
.
我原以为这alias_attribute :new, :OLD
允许您指定一个可以在ActiveRecord/ActiveRelation
查询中使用的名称。从我在下面看到的(在 中测试rails console
)来看,情况并非如此。
最终目标是通过让每个模型都有一个ID
属性等,让遗留系统在 Rails 传统方法中“行动”……
型号定义:
# app/models/organization.rb
class Organization < ActiveRecord::Base
self.table_name = "ORGANIZATION"
self.primary_key = "ORGANIZATION_ID"
alias_attribute :id, :ORGANIZATION_ID
end
不工作:
Organization.select(:id)
=>invalid column name 'id'
Organization.select(:ID)
=>invalid column name 'ID'
Organization.select("ID")
=>invalid column name 'ID'
是否有效:
Organization.select(:organization_id)
=><finds record>
Organization.select(:ORGANIZATION_ID)
=><finds record>
Organization.select("organization_id")
=><finds record>
Organization.select("ORGANIZATION_ID")
=><finds record>