ActiveRecord 查询支持:select
参数,它允许您定义想要以字符串形式返回给您的字段。
通常人们使用类似的东西:
:select => 'field1, field2'
如果您知道数据库服务器的原始查询语言,则可以在选择字符串中使用它。使用 SQL 选择字段时的选项之一是使用as
修饰符:
select field1 as the_first_field, field2 as the_second_field
并且数据库将使用新字段名称而不是旧字段名称返回字段。如果您的数据库支持,那么这是一种管理遗留字段的简单方法,这些字段的命名方式与 Rails 冲突。
请参阅“学习喜爱 ActiveRecord 的 :select 参数”ActiveRecord 的五个技巧 http://blog.grayproductions.net/articles/five_activerecord_tips" and "选择特定字段 http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields” 在 Ruby on Rails 指南中。
这是我的 Rails 应用程序之一的示例,使用rails console
访问我的 Postgres 数据库:
ruby-1.9.2-p180 :007 > dn = DomainName.first
=> #<DomainName id: 1, domain_name: "ip72-208-155-230.ph.ph.cox.net", created_at: "2010-04-20 05:53:22", updated_at: "2010-04-20 05:53:22">
ruby-1.9.2-p180 :008 > dn = DomainName.first(:select => 'id, domain_name as dn')
=> #<DomainName id: 1>
ruby-1.9.2-p180 :009 > dn['id']
=> 1
ruby-1.9.2-p180 :010 > dn['dn']
=> "ip72-208-155-230.ph.ph.cox.net"