是否可以在与SQL表达式对应的activerecord中定义虚拟属性?
我喜欢虚拟属性,但这可以在数据库级别工作:说我有一个字段age
,我想添加一个等于age/5
的“虚拟字段” age_quintile
,但是这样的方式是可以说:
Person.select(:age_quintile,"agv(height)"). group(:age_quintile). order(:age_quintile)
对应于:
SELECT (age/5) as age_quintile, avg(height) FROM persons GROUP BY (age/5) ORDER BY (age/5);
要么
Person.maximum(:age_quintile)
对应于
SELECT max(age/5) FROM persons;
所以,我想我会在模型中声明这样的属性,如:
class Person < ActiveRecord::Base ... magic_attribute :age_quintile, :integer, 'age/5' end
最后一位是SQL表达式,并且从字符串转换是必需的。
有没有办法用香草ActiveRecord或一些gem做到这一点?
更新
希望在模型中声明这些属性的原因,而不是 – 如所建议的那样 – 在select中使用别名表达式是我们希望属性参与通用查询API并且作为任何其他属性出现给API的用户。 所以以下应该是可能的:
class PeopleController Person. select( group_columns + select_columns ). group(group_columns). search(group_columns) end end
和查询字符串?group=age_quintile&measurements=height
将导致:
SELECT (age/5) as age_quintile, min(height), avg(height), max(height) FROM persons GROUP BY (age/5) ORDER BY (age/5);
这是可能的。 更重要的是,它由ActiveRecord自动完成:
@people = Person. select('(age/5) as age_quintile, height'). group(:age_quintile). order(:age_quintile) person = @people.first person.age_quintile # => age_quintile value (person.age / 5)