将SQL查询转换为Rails查询

时间:2012-10-10 20:30:56

标签: sql ruby-on-rails

我可以使用find_by_sql来完成此任务,但如果可能的话,我想以Rails方式执行此操作。

我的SQL查询如下所示:

SELECT regions.id, max(updated_at) FROM demographics 
JOIN regions ON (regions.id = demographics.region_id) 
JOIN region_stats ON (region_stats.region_id = regions.id) 
WHERE region_stats.income_level = 1    
GROUP BY demographics.region_id;

有没有办法将它干净利落地转换为Rails?

2 个答案:

答案 0 :(得分:1)

Demographic.find(:all,
  :conditions=>[
    "region_stats.income_level = ?",
    1
  ],
  :joins=>"as demographics JOIN regions ON (regions.id = demographics.region_id) JOIN region_stats ON (region_stats.region_id = regions.id)",
  :group=>"demographics.region_id",
  :select=>"regions.id, demographics.max(updated_at)"
)

答案 1 :(得分:1)

未测试:

Demographic.joins(:region => [:region_stats]).select('demographics.region_id, max(demographics.updated_at) as `max_date`').where(:region_stats => {:income_level => 1}).group('demographics.region_id')