There are many questions that will help you convert a specific SQL query into an ActiveRecord query.
Are there any help / guidance tools [online] for automatic conversion?
here is the tool you are looking for: http://www.scuttle.io/