开发者

Query for specific columns with rails 3

开发者 https://www.devze.com 2023-03-21 01:04 出处:网络
I want to run a query that only returns the columns that I specify. I haven\'t been able to find a good way to do this with rails 3. My first attempt was

I want to run a query that only returns the columns that I specify. I haven't been able to find a good way to do this with rails 3. My first attempt was

query = transactions.group("month").
                     select("DATE_FORMAT(transactions.purchased_at, '%Y-%m') as month")
rows = ActiveRecord::Base.connection.select_all(query.to_sql)

but this also includes transactions.* in the select. I have managed to get it working like this:

query = transactions.group("month")
query.select_values = [
  "DATE_FORMAT(transactions.purchased_at, '%Y-%m') as month", 
  "count(*) as开发者_JAVA技巧 total"
]
rows = ActiveRecord::Base.connection.select_all(query.to_sql)

This seems pretty nasty though, is there a better way to do it?


If I understand what you're looking for you can just use the select ARel method

User.select('id').where('')
=> [#<User id: 2>, #<User id: 4>....
0

精彩评论

暂无评论...
验证码 换一张
取 消