views:

124

answers:

2

What is the best practice where should I put SQL queries in Rails?

  • Should I create the methods in models for example: find_all_public_items where I'm using the find methods with all the conditions, and then using them in controllers. Like that I have all the queries in one place but I miss the flexibility that every query should be exactly suited for the need.

  • Should I just use the find/find_by_sql in controllers - like this I'm not creating thousands of methods but i'm loosing control on how the controllers are sucking data from database.

+8  A: 

Put everything model-related in the model. Period.

Ben Alpert
+4  A: 

You should put them in your models. You might want to investigate named scopes too.

John Topley
That named scopes mechanism looks pretty cool: short and sweet macro-ish thing to generate the queries given just a hint at the "where" clause for the need of the day. Thanks.
Roboprog
Also, I like the fact that you pointed out something to make it easier, rather than simply saying "thou shalt" (implied: even if it hurts, etc)
Roboprog
Named scopes are particularly nice because you can chain them together.
cpm