0

I could just use a find_by_sql to accomplish this, but I'd like to do it the Rails way if possible.

My SQL query looks like this:

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;

Is there a way to convert this cleanly to Rails?

1
  • It's not clear what table the field updated_at belongs to, can you clarify? Commented Oct 10, 2012 at 20:58

2 Answers 2

1

Untested:

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')
Sign up to request clarification or add additional context in comments.

Comments

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)"
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.