3

I'm setting up a custom query that uses a range of OR statements in conjunction with BETWEEN statements and a final GROUP BY id HAVING COUNT(*) >= #{tolerance}. Not to mention INNER and LEFT join operations.

I would assume that it would not be possible to setup using active record. So I used the Model.connection.select_all() command to fire a query. This works, but how do I not map all of the rows to that specific model?

1 Answer 1

11

Rails is pretty powerful especially if you are using Rails 3 & ARel. So I wouldn't be surprised if you actually could write your query using rails.

However, there will always be times when writing raw SQL is desired.

To do that, instead of Model.connection use Model.find_by_sql(QUERY_STRING).

This way the query will get parsed for you automatically just make sure you only select "model.*"

Sign up to request clarification or add additional context in comments.

1 Comment

This is probably the best solution, to go further, if you are using PostgreSQL, you might want to create a view for this query : see KnowSQL presentation slide between 70 and 72

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.